Reputation: 53
I'm want to auto wire the beans which are the var args aruments for my constructor.
Can I do that, if yes how can I achieve?
Here is the code I'm trying:
Public class ServiceImpl implements Service{
private Set<Rules> rules = new HashSet<Rules>();
public ServiceImpl(Rules... args) {
for (Rules r : args) {
rules.add(r);
}
}
//...
}
I'm trying to inject in spring-config.xml
like below:
<bean id = "check" class="ServiceImpl">
<constructor-arg ref="notEmpty"></constructor-arg>
<constructor-arg ref="check"></constructor-arg>
</bean>
Is there a way that I can achieve this with annotations and without passing constructor args
here.
Upvotes: 1
Views: 303
Reputation: 23171
Yes, with annotations you can add @Autowired to the constructor and the IoC container will wire in all the Rules instances that are registered in the context:
@Component
public class ServiceImpl implements Service{
private Set<Rules> rules = new HashSet<Rules>();
@Autowired
public ServiceImpl(Rules... args) {
for (Rules r : args) {
rules.add(r);
}
}
}
Upvotes: 2