-1

我有以下课程:

public class ProducerWrapper<K, V> {

    Producer<K, V> producer;
    ThreadPoolExecutor threadPoolExecutor;

    @Autowired
    public ProducerWrapper(Properties p, int poolsize) {
        ......
        log.info("Created kafka producer");
    }
 ....

我尝试将其注入不同的服务:

@Service
public class mainService{

    @Qualifier("ProducerX")
    @Autowired
    private ProducerWrapper<Long,CustomObject1> p1;

    @Autowired
    @Qualifier("ProducerY")
    private ProducerWrapper<Long,CustomObject2> p2;

我创建了以下配置:

@Configuration
@ComponentScan("main_package..")

public class MyConf {

    @Bean(name = "ProducerX")
    public ProducerWrapper<Long, CustomObject1> createProducerWrapper() throws IOException {
      FileInputStream propertiesFile = new FileInputStream("producerx.properties");
      properties = new Properties();
      properties.load(propertiesFile);
      return new ProducerWrapper<>(properties,5);
    }

    @Bean(name = "ProducerY")
    public ProducerWrapper<Long, CustomObject2> createProducerWrapper() throws IOException {
      FileInputStream propertiesFile = new FileInputStream("producery.properties");
      properties = new Properties();
      properties.load(propertiesFile);
      return new ProducerWrapper<>(properties,5);
    }
}

如您所见,每个生产者都有不同的属性文件。我得到的错误如下:

    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.

如果我删除构造函数顶部的自动装配注释,我会得到一个不同的错误,即 Spring 找不到默认构造函数。

此外,在日志中,我看到以下消息,表明构造函数中的所有内容都已运行:

2020-06-24 12:14:49.331  INFO 30912 --- [           main] c.a.a.ProducerWrapper      : Created kafka producer

我究竟做错了什么 ?

4

2 回答 2

0

你有这个签名:

 @Autowired
    public ProducerWrapper(Properties p, int poolsize) {
...

您尚未提供要自动装配的“poolsize”参数。即,您的配置中不存在可以自动装配到此变量中的整数。

要解决此问题:创建一个包装 int 值的 PoolSize 类。然后在您的配置中创建一个 PoolSize 对象以进行自动装配。

它在错误输出中说:

...No qualifying bean of type 'int' available: expected at least 1 bean which qualifies as autowire candidate.
于 2020-06-24T09:28:19.697 回答
0

我在以下stackoverflow帖子中找到了解决方案

底线:

  1. ProducerWrapper 类中的构造函数不应有任何注释:
    //None annotation above constructor
    public ProducerWrapper(Properties p, int poolsize) {
        ......
        log.info("Created kafka producer");
    }
  1. 就像我在主要评论中粘贴的那样,为 bean 创建一个配置类。3.从ProducerWrapper中移除Service annoatipn
于 2020-06-24T13:53:47.123 回答