我在 spring 中有一个配置文件,我想为 spring 中特定 @Component
的每个实例定义一个构造函数参数。我怎样才能做到这一点?
@Component
public class MyComponent {
public MyComponent(String config) {}
}
在我的application.yml
中我想定义这样的东西:
myconfig:
- config1
- config2
- config3
我想让 spring 在 application.yml
中的每个配置条目创建一个实例。那可能吗?
谢谢
最佳答案
Spring 无法自动执行此操作。您必须按照 @Mick 建议通过子类化来单独定义 bean。首先,从基类中删除@Component注解:
public class MyComponent {
public MyComponent(String config) {}
}
为每个配置创建您需要的任意数量的扩展作为@Component:例如:
@Component
public class MyComponentConfig1 extends MyComponent {
public MyComponentConfig1(@Value("myconfig.config1") String config) {
super(config);
}
}
注册 bean 时,Spring 将这些值注入(inject)到构造函数中。
关于java - Spring bean 的多个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46428342/