简体   繁体   English

来自@Configuration的Autowire bean

[英]Autowire bean from @Configuration

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: {}". 我是Spring的新手,我遇到异常“找不到依赖项的类型为[int]的合格bean:期望至少有1个bean符合此依赖项的自动装配候选。依赖注释:{}”。 When i try the below approach. 当我尝试以下方法时。

This is the configuration for the RestTemplate 这是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 您需要注入RestTemplate ,而不是config类

@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. 创建一个属性文件(*.properties)并将其放置在src/main/resources文件夹中。 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. @Value是一个Spring注释,它在classpath上搜索属性文件,并在创建Spring bean时注入值。

This is to do with the following line of code in your configuration 这与配置中的以下代码行有关

public RestTemplate createRestTemplate(int maxTotalConn, int maxPerChannel, int connTimout);

Spring expects the three integer parameters to be available when it creates the bean. Spring希望在创建bean时三个整数参数可用。 Where are the values supposed to come from. 价值应该从何而来。

You can use make use of property files (Spring property abstraction) to inject the 3 fields 您可以使用利用属性文件(Spring属性抽象)来注入3个字段

First option supply the parameters in your environment and inject the Environment instead 第一种选择是在您的环境中提供参数,然后注入环境

public RestTemplate createRestTemplate(Environment env){
    int maxTotalConn = env.getRequiredProperty("pool.maxSize" , Integer.class);
//lookup remaining parameters
}

Then make sure you have a property file eg http-connection-pool.properties containg the settings. 然后确保您有一个属性文件,例如包含设置的http-connection-pool.properties。 Specify it on your configuration file 在配置文件上指定它

@Configuration
@PropertySource("classpath:http-connection-pool.properties")
public class RestClientConfig {

}

Then add the http-connection-pool.properties to the root of your classpath 然后将http-connection-pool.properties添加到类路径的根目录

You can also use the @Value annotation with property placheolders to achieve the same 您还可以将@Value注释与属性placheolders结合使用以实现相同的效果

@Bean
public RestTemplate createRestTemplate(@Value("${pool.maxSize}")int maxTotalConn, @Value("${pool.maxPerChannel}")int maxPerChannel, @Value("${pool.connectionTimeout}")int connTimout) {
//more code
}

However with this approach you need to register a PropertySourcesPlaceholderConfigurer as follows 但是,使用这种方法时,您需要按如下所示注册PropertySourcesPlaceholderConfigurer

@Bean
public static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer(){
return new PropertySourcesPlaceholderConfigurer();
}

And you still need to add the property files on your configuration class 而且您仍然需要在配置类上添加属性文件

Configuration classes are used to tell spring which objects you want to use as beans. 配置类用于告诉spring您想将哪些对象用作bean。 You have properly marked RestTemplate class as a @Bean, so you can easily autowire it into other classes through application. 您已将RestTemplate类正确地标记为@Bean,因此可以轻松地通过应用程序将其自动装配到其他类中。

@Autowired
private RestTemplate restTemplate;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM