Reputation: 1336
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. 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:
myconfig:
- config1
- config2
- config3
I would like to make spring create one instance per config entry in the application.yml
. Is that possible?
Thanks
Upvotes: 0
Views: 1707
Reputation: 9622
There's no way to do this automatically with Spring. You would have to define the beans individually probably by subclassing as @Mick suggested. Firstly, remove the @Component annotation from the base class:
public class MyComponent {
public MyComponent(String config) {}
}
Create however many extensions of this you require as @Components for each config: e.g.:
@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.
Upvotes: 1
Reputation: 973
You want to create 3 beans with one annotation? Not possible as far as I know. Why not create 3 subclasses and pull in the configuration values with @Resource annotations? And btw: you must provide a default constructor, because that is the one being called.
Upvotes: 1