I have a spring application in which I am trying to inject many beans of the same type. I do not know how many of these beans there will be before runtime, so it seems natural to use the factory pattern, as I cannot configure each bean in my java config class. However, these beans need to have some of their fields wired by Spring, and when I create them with "new" in my factory, they are of course not Spring managed.
Is there a way to have the beans I create in my factory class be managed by Spring? Or is the factory pattern the wrong way to go about this?
I am fairly new to posting, so please let me know if any more information is necessary.
You can define a beanFactory wired with the dependencies needed for your bean, then manually injected them in each new bean created by the beanFactory. For example:
public class MyBean {
private Dependency1 dep1;
private Dependency2 dep2;
public MyBean(Dependency1 dep1, Dependency2 dep2) {
this.dep1 = dep1;
this.dep2 = dep2;
}
}
@Component
public class MyBeanFactory {
@Autowired
private Dependency1 dep1;
@Autowired
private Dependency2 dep2;
public MyBean createInstance() {
return new MyBean(dep1, dep2);
}
}
@Component
public class MyBeanConsumer {
@Autowired
private MyBeanFactory myBeanFactory;
public void foo() {
final MyBean bean = myBeanFactory.createInstance();
}
}