Getting Spring Application Context

来源:互联网 发布:江苏卫视网络电视直播 编辑:程序博客网 时间:2024/04/29 16:15

Is there a way to statically/globally request a copy of the ApplicationContext in a Spring application?

Assuming the main class starts up and initializes the application context, does it need to pass that down through the call stack to any classes that need it, or is there a way for a class to ask for the previously created context? (Which I assume has to be a singleton?)

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.

0 0
原创粉丝点击