首页 > 解决方案 > 通过构造函数注入 bean 依赖项时出现 NoSuchBeanDefinitionException

问题描述

我正在尝试将配置 bean 注入到我的服务中。为此,我创建了一个单独的类 EncryptionProps

public class EncryptionProps {
    @Getter
    @Setter
    @Value("${kafka.properties.security.keyreuseinterval}")
    private long keyReuseInterval;
}

然后,我正在创建另一个配置类来将其注册为 bean

@Configuration
public class EncryptionConfig {
@Bean
public EncryptionProps encryptionProps() {
    return new EncryptionProps();
}}

这就是我在我的服务类中调用它的方式:

@Service
public class EncryptionService {   
private final long keyReuseInterval;

//some more declarations    

@Autowired
public EncryptionService(SchemaProcessor schemaProcessor, CryptoLib crypto, EncryptionProps encryptionProps) {
    this.schemaProcessor = Preconditions.checkNotNull(schemaProcessor, "schemaProcessor cannot be null.");
    this.crypto = Preconditions.checkNotNull(crypto, "CryptoLib must be provided");
    this.keyReuseInterval = encryptionProps.getKeyReuseInterval();
} 

但是,当我运行此程序时,我收到以下错误 - org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.example.sinkad.kafka.util.EncryptionProps' available: expected at least 1 bean which有资格成为 autowire 候选人。依赖注解:{@org.springframework.beans.factory.annotation.Autowired(required=true)}

从昨天开始,我就一直坚持这一点。我已经尝试了很多关于这个的stackoverflow问题,但到目前为止没有任何帮助。任何人都可以帮助我解释为什么 Spring 没有找到这个 bean。我什至尝试在 EncryptionConfig 类上添加 @ComponentScan。但这也没有奏效。或者,如果您可以向我指出一些与之相关的资源。

谢谢!

更新:

这是我的主要课程:

package com.example.sinkad;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
}}

标签: javaspringspring-boot

解决方案


在团队成员的帮助下,我终于能够解决这个问题。我仍然不确定是什么问题,但这是我们所做的:

1) 将 keyReuseInterval 值移动到另一个配置类,这将为 EncryptionProps 对象创建对象

public class EncryptionProps {
@Getter
@Setter
private long keyReuseInterval;  
}

这是配置类

@Configuration
public class CryptoConfig {

@Value("${kafka.properties.security.keyreuseinterval}")
private long keyReuseInterval;

@Bean
public EncryptionProps encryptionProps() {
    EncryptionProps encryptionProps = new EncryptionProps();
    encryptionProps.setKeyReuseInterval(keyReuseInterval);
    return encryptionProps;
}

}

2)我们在服务类中调用encryptionProps,类似于之前:

 @Autowired
public EncryptionService(SchemaProcessor schemaProcessor, CryptoLib crypto, EncryptionProps encryptionProps) {
    this.schemaProcessor = Preconditions.checkNotNull(schemaProcessor, "schemaProcessor cannot be null.");
    this.crypto = Preconditions.checkNotNull(crypto, "CryptoLib must be provided");
     this.keyReuseInterval = encryptionProps.getKeyReuseInterval();
}

我不确定这是如何解决问题的。但是,思想会与大家分享。再次感谢大家的建议。


推荐阅读