
Originally Posted by
mdeinum
Let the Spring configured class which needs access to the ApplicationCOntext implement the ApplicationContextAware interface, the context will be automatically injected.
The thing is, the class is not spring configured.
It is just a class, which will be instantiated by a 3rd party tool, but still needs to access a DAO.
But still, the ApplicationContextAware is a quite useful hint. What my Solution would be:
Code:
public class BeanFactoryAccessor implements ApplicationContextAware , InitializingBean{
private static final Log LOG = LogFactory.getLog(BeanFactoryAccessor.class);
private static BeanFactory _ctx = null;
public BeanFactoryAccessor() {
LOG.info("Creating BeanFactoryAccessor...");
}
public static BeanFactory getBeanFactory() {
if (_ctx==null){
BeanFactory bf = new ClassPathXmlApplicationContext("applicationContext.xml");
bf.getBean("userDAO");
LOG.fatal("Have no beanfactoy.... something must be wrong here");
throw new RuntimeException("Have no beanfactoy.... something must be wrong here");
}
return _ctx;
}
/* (non-Javadoc)
* @see org.springframework.context.ApplicationContextAware#setApplicationContext(org.springframework.context.ApplicationContext)
*/
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
LOG.info("Setting required ApplicationContext...");
_ctx=applicationContext;
}
/* (non-Javadoc)
* @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
*/
public void afterPropertiesSet() throws Exception {
Assert.notNull(_ctx);
}
}
So now, I could do something like:
Code:
UserDAO userDAO = (UserDAO) BeanFactoryAccessor.getBeanFactory().getBean("userDAO");
What do think abaout that?