I am new to Spring, I am getting the exception "No qualifying bean of type [int] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}". When i try the below approach.
This is the configuration for the RestTemplate
@Configuration
public class RestClientConfig {
@Bean
public ObjectMapper getObjMapper(){
return new ObjectMapper();
}
@Bean
public RestTemplate createRestTemplate(int maxTotalConn, int maxPerChannel, int connTimout) {
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
connectionManager.setMaxTotal(maxTotalConn);
connectionManager.setDefaultMaxPerRoute(maxPerChannel);
RequestConfig config = RequestConfig.custom().setConnectTimeout(connTimout).build();
CloseableHttpClient httpClient = HttpClientBuilder.create().setConnectionManager(connectionManager)
.setDefaultRequestConfig(config).build();
ClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);
RestTemplate restTemplate = new RestTemplate(factory);
restTemplate.setErrorHandler(new RestResponseErrorHandler());
restTemplate.setMessageConverters(createMessageConverters());
return restTemplate;
}
private List<HttpMessageConverter<?>> createMessageConverters() {
List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
MappingJackson2HttpMessageConverter jsonMessageConverter = new MappingJackson2HttpMessageConverter();
jsonMessageConverter.setObjectMapper( getObjMapper());
messageConverters.add(jsonMessageConverter);
return messageConverters;
}
}
When i try to access like this, it causing the exception mentioned above.
@Autowired
private RestClientConfig restTemplate;
ResponseEntity<String> response2 = restTemplate.createRestTemplate(100, 100, 100).exchange( url, HttpMethod.GET, entity , String.class );
Please can some one help and point me the correct approach and what i am doing anything wrong?
You need to inject the RestTemplate
, not the config class
@Autowired
private RestTemplate restTemplate;
instead of:
@Autowired
private RestClientConfig restTemplate;
EDIT
Here is one way to pass your arguments to your class:
//EXAMPLE @Value("${propFile.maxTotalConn}")
@Bean
public RestTemplate createRestTemplate(@Value("${propFile.maxTotalConn}") int maxTotalConn, @Value("${propFile.maxPerChannel}") int maxPerChannel, connTimoutint connTimout) {
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
connectionManager.setMaxTotal(maxTotalConn);
connectionManager.setDefaultMaxPerRoute(maxPerChannel);
...
}
EXPLANATION
Create a properties file (*.properties)
and place in your src/main/resources
folder. Include your properties in it as the code above suggests. @Value
is a Spring
annotation that searches for the properties file on the classpath
and injects the values while creating your Spring bean.