[英]Multiple instances of a bean Spring
I have a config file in spring which I want to define a constructor parameter for each instance of a particular @Component
that I have in spring. 我在spring中有一个配置文件,我想为spring中具有的特定
@Component
每个实例定义一个构造函数参数。 How can I do that? 我怎样才能做到这一点?
@Component
public class MyComponent {
public MyComponent(String config) {}
}
and in my application.yml
I want to define something like this: 在我的
application.yml
我想定义如下内容:
myconfig:
- config1
- config2
- config3
I would like to make spring create one instance per config entry in the application.yml
. 我想让spring在
application.yml
中为每个配置条目创建一个实例。 Is that possible? 那可能吗? Thanks
谢谢
You want to create 3 beans with one annotation? 您想用一个注解创建3个bean? Not possible as far as I know.
据我所知不可能。 Why not create 3 subclasses and pull in the configuration values with @Resource annotations?
为什么不创建3个子类并使用@Resource批注引入配置值? And btw: you must provide a default constructor, because that is the one being called.
顺便说一句:您必须提供一个默认的构造函数,因为这是被调用的那个。
There's no way to do this automatically with Spring. Spring无法自动执行此操作。 You would have to define the beans individually probably by subclassing as @Mick suggested.
您可能必须通过@Mick建议的子类化来分别定义bean。 Firstly, remove the @Component annotation from the base class:
首先,从基类中删除@Component批注:
public class MyComponent {
public MyComponent(String config) {}
}
Create however many extensions of this you require as @Components for each config: eg: 但是,为每个配置创建您需要的许多扩展作为@Components:例如:
@Component
public class MyComponentConfig1 extends MyComponent {
public MyComponentConfig1(@Value("myconfig.config1") String config) {
super(config);
}
}
Where the values are injected into your constructor for you by Spring when registering the beans. Spring在注册bean时将这些值注入到您的构造函数中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.