Java 构造函数中带有参数的Autowire类失败
我有以下课程:Java 构造函数中带有参数的Autowire类失败,java,spring,Java,Spring,我有以下课程: public class ProducerWrapper<K, V> { Producer<K, V> producer; ThreadPoolExecutor threadPoolExecutor; @Autowired public ProducerWrapper(Properties p, int poolsize) { ...... log.info("Created k
public class ProducerWrapper<K, V> {
Producer<K, V> producer;
ThreadPoolExecutor threadPoolExecutor;
@Autowired
public ProducerWrapper(Properties p, int poolsize) {
......
log.info("Created kafka producer");
}
....
如果我删除构造函数顶部的自动连线注释,我将得到另一个错误,Spring无法找到默认构造函数
此外,在日志中,我看到以下消息,表明构造函数中的所有内容都已运行:
2020-06-24 12:14:49.331 INFO 30912 --- [ main] c.a.a.ProducerWrapper : Created kafka producer
我做错了什么?您有以下签名:
@Autowired
公共ProducerRapper(属性p,int池大小){
...
您尚未提供要自动连接的“poolsize”参数。即,配置中没有可自动连接到此变量的整数
要解决此问题,请创建一个封装int值的PoolSize类。然后在配置中创建一个要自动连接的PoolSize对象
它在错误输出中表示:
...No qualifying bean of type 'int' available: expected at least 1 bean which qualifies as autowire candidate.
我在下面的stackoverflow中找到了解决方案 底线:
p2是否也被设置为@Autowired?在您的代码中不是这样。@PatrickSantana是的,的确,我更新了postSo,所以我不能自动连接基本体?需要包装它们或使用Integer对象吗?您可以自动连接基本体,但当您想使用超过1个int时,您会遇到问题。为了避免这种情况,请将int包装到对象类型中…现在您的代码将显示为对于像这样的简单参数,IMO包装器也不是很好的做法,除非有许多逻辑上组合在一起的分组值。
@Value(${my.pool.size})int-poolSize
也适用于此用例。您是对的,它可以工作,但是当您想要连接另一个int时会发生什么?当您使用@Bean
通过配置创建Bean时,您甚至不应该有@Component
注释。@Component
甚至可能导致额外的Beann正在构造(或启动时出错)。我正要这么说。您已经通过java config创建了bean。我是否需要在服务类中保留包装器的Autowire和限定符ontop?
Error creating bean with name 'ProducerWrapper' defined in file [..../ProducerWrapper.class]: Unsatisfied dependency expressed through constructor parameter 1;
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'int' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
Parameter 1 of constructor in com.xx.xx.ProducerWrapper required a bean of type 'int' that could not be found.
2020-06-24 12:14:49.331 INFO 30912 --- [ main] c.a.a.ProducerWrapper : Created kafka producer
...No qualifying bean of type 'int' available: expected at least 1 bean which qualifies as autowire candidate.
//None annotation above constructor
public ProducerWrapper(Properties p, int poolsize) {
......
log.info("Created kafka producer");
}