How to provide current BeanFactory as constructor argument
I have a singleton class which I would like to be created using Spring's IoC. This class needs to instantiate a dynamic number of other objects using IoC as well. Thus, this class needs the BeanFactory passed in as a constructor argument. How can I do this?
Here is the general structure I was planning. I am fairly new to Spring IoC, so I am also open to changing this structure if it does not fit well in Spring.
public class Main
{
public static void main(String[] args)
{
ApplicationContext context =
new ClassPathXmlApplicationContext(new String[]{"applicationContext.xml"});
MySingletonInterface instance = context.getBean(MySingletonInterface.class);
instance.foo();
}
}
public class MySingletonClass implements MySingletonInterface
{
public MySingletonClass(BeanFactory beanFactory开发者_运维百科)
{
this.beanFactory = beanFactory;
}
public void foo()
{
for( ..... )
{
NeedManyInstances instance = beanFactory.getBean(NeedManyInstances.class);
....
}
}
}
The easiest way is to declare constructor as @Autowired
(make sure that application context is configured for use of annotation-based configuration with <context:annotation-config/>
):
@Autowired
public MySingletonClass(BeanFactory beanFactory) { ... }
Another option is to make your class implement BeanFactoryAware
and use setBeanFactory()
method instead of constructor.
精彩评论