我正在尝试将配置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:没有合格的bean of Type'com.example.sinkample.sinkamd.kafka.kafka.util.encrypterment.encryptermptprops'至少可用:预期至少1 bean符合自动候选人的资格。依赖项注释:{@org.springframework.beans.factory.annotation.autowired(quilt = true)}
我从最后一天开始就被困住了。我已经尝试了很多关于此问题的问题,但是到目前为止都没有任何帮助。任何人都可以在为什么春天找不到这个豆子的情况下帮助我。我什至尝试在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);
}}
尝试以下类似:
@Component
class EncryptionProps {
final String keyreuseinterval;
// Use @Autowired to get @Value to work.
@Autowired
EncryptionProps(
@Value("${kafka.properties.security.keyreuseinterval}") final String keyreuseinterval) {
this.keyreuseinterval = keyreuseinterval;
}
}
我终于能够在团队成员的帮助下解决这个问题。我仍然不确定是什么问题,但这是我们所做的:
1)将KeyReuseInterval值移至另一个配置类,该类将为EncryptionProps Object创建对象
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();
}
我不确定如何解决问题。但是想到会和你们分享。再次感谢您的建议。