2010-11-24
通过ApplicationContextAware获取bean
博客分类: Spring
BeanSpring.
加载Spring配置文件时,如果Spring配置文件中所定义的Bean类实现了ApplicationContextAware 接口,那么在加载Spring配置文件时,会自动调用ApplicationContextAware 接口中的
public void setApplicationContext(ApplicationContext context) throws BeansException
方法,获得ApplicationContext 对象。
前提必须在Spring配置文件中指定该类。
Java代码
1.public class SpringContextHolder implements ApplicationContextAware {
2.
3. /**
4. * 以静态变量保存ApplicationContext,可在任意代码中取出ApplicaitonContext.
5. */
6. private static ApplicationContext context;
7.
8. /**
9. * 实现ApplicationContextAware接口的context注入函数, 将其存入静态变量.
10. */
11. public void setApplicationContext(ApplicationContext context) {
12. SpringContextHolder.context =context;
13. }
14. public static ApplicationContext getApplicationContext() {
15. return context;
16. }
17. /**
18. * 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型.
19. */
20. public static <T> T getBean(String name) {
21. return (T) context.getBean(name);
22. }
23.}
bean中:
Java代码
1.<bean id="springContextHolder" class="com.enation.framework.context.spring.SpringContextHolder" />
调用:
Java代码
1.ICartManager cartManager = SpringContextHolder.getBean("cartManager");
正常情况:
Java代码
1.public class AppManager extends ContextLoaderListener implements ServletContextListener {
2.
3. private ServletContext context;
4. private WebApplicationContext webApplicationContext;
5.
6. public void contextInitialized(ServletContextEvent sce) {
7. this.context = sce.getServletContext();
8. this.webApplicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(context);
9. this.context.setAttribute("WEBAPPLICATIONCONTEXT", webApplicationContext);
10.
11. }
Java代码
1.HttpSession session = request.getSession();
2.WebApplicationContext webApplicationContext = (WebApplicationContext)session.getServletContext().getAttribute("WEBAPPLICATIONCONTEXT");
3.UnsubscribeEmailFacade unsubscribeEmailFacade = (UnsubscribeEmailFacade)webApplicationContext.getBean("unsubscribeEmailFacade");
|