Getting Spring Application Context
If the object that needs access to the container is a bean in the container, just implement the BeanFactoryAware or ApplicationContextAware interfaces.
If an object outside the container needs access to the container, I've used a standard GoF singleton pattern for the spring container. That way, you only have one singleton in your application, the rest are all singleton beans in the container.
You can implement ApplicationContextAware
or just use @Autowired
:
public class SpringBean {
@Autowired
private ApplicationContext appContext;
}
SpringBean
will have ApplicationContext
injected, within which this bean is instantiated. For example if you have web application with a pretty standard contexts hierarchy:
main application context <- (child) MVC context
and SpringBean
is declared within main context, it will have main context injected;
otherwise, if it's declared within MVC context, it will have MVC context injected.
Here's a nice way (not mine, the original reference is here: http://sujitpal.blogspot.com/2007/03/accessing-spring-beans-from-legacy-code.html
I've used this approach and it works fine. Basically it's a simple bean that holds a (static) reference to the application context. By referencing it in the spring config it's initialized.
Take a look at the original ref, it's very clear.