Home > Back-end >  RestTemplate bean is not found in the service layer class even though i have autowired it
RestTemplate bean is not found in the service layer class even though i have autowired it

Time:09-29

When i run the application its working fine but when i build the app its throwing this exception - No qualifying bean of type 'org.springframework.web.client.RestTemplate' available: expected at least 1 bean which qualifies as autowire candidate.

below is the code snippet

As a note, i have created this bean in the main application, so its scope is throughout the application but it's still not found. Anyone can offer some help?

@Autowired
RestTemplate restTemplateBean;

@Bean("restTemplateBean")
    public RestTemplate restTemplateBean(RestTemplateBuilder builder) throws IOException, CertificateException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
        SSLContext sslContext = new SSLContextBuilder()
                .loadTrustMaterial(new URL("file:src/main/resources/itsm_qa_api-keystore.jks"), "changeit".toCharArray()).build();

        SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext);

        HttpClient httpClient = HttpClients.custom()
                .setSSLSocketFactory(socketFactory)
                .build();

        return builder
                .requestFactory(() -> new HttpComponentsClientHttpRequestFactory(httpClient))
                .build();
    }

CodePudding user response:

As you have defined the specific name for your Bean as "restTemplateBean", when you want to inject that specific bean you need to qualify the bean name as well.

I think you can do it as below:

@Autowired
@Qualifier("restTemplateBean")
RestTemplate restTemplate;

Also you can use @Qualifier with combination of constructor injection like this:

public class ClassA {

private RestTemplate restTemplate;

public ClassA(@Qualifier("restTemplateBean") RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

}

CodePudding user response:

I had forgot to add a bean in Test configuration class, that is why i was getting this exception. Thanks everyone

  • Related