SpringContextUtil获取上下文中bean
2018-01-25 16:47
513 查看
一.SpringContextUtil类
public class SpringContextUtil implements ApplicationContextAware { private static ApplicationContext applicationContext; // Spring应用上下文环境 /* * 实现了ApplicationContextAware 接口,必须实现该方法; * 通过传递applicationContext参数初始化成员变量applicationContext */ public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { SpringContextUtil.applicationContext = applicationContext; } public static ApplicationContext getApplicationContext() { return applicationContext; } @SuppressWarnings("unchecked") public static <T> T getBean(String name) throws BeansException { return (T) applicationContext.getBean(name); } public static <T> T getBean(Class<T> clazz) throws BeansException { return (T) applicationContext.getBean(clazz); } }
xml配置
web.xml<servlet> <servlet-name>DispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet </servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:SpringServlet.xml</param-value> </init-param> <!--随tomcat启动一起加载 --> <load-on-startup>1</load-on-startup> <async-supported>true</async-supported> </servlet>
SpringServlet.xml
<!-- 可通过SpringContextUtil获取Spring容器中的任何bean --> <bean id="springContextUtil" class="com.kylin.aep.utils.SpringContextUtil" scope="singleton" />
这样,在根据SpringServlet.xml初始化上下文时,会自动调用setApplicationContext()方法去获取ApplicationContext。
使用
PermeateService permeateServiceImpl = SpringContextUtil.getBean(PermeateServiceImpl.class);
相关文章推荐
- 获取SpringMVC上下文bean实例-SpringContextUtil
- 一种获取spring环境上下文方法:SpringContextUtil
- spring3.0的BeanFactory上下文context获取不到bean
- 一种获取spring环境上下文方法:SpringContextUtil
- 一种获取spring环境上下文方法:SpringContextUtil
- Spring3MVC通过SpringContextUtil获取上下文(与不使用对比)
- 通过SpringContextUtil获取spring环境上下文
- spring获取applicationContext.xml中bean内容
- Java类获取Spring的applicationContext.xml文件中的bean
- java类中从spring的ApplicationContext.xml中获取bean
- Spring - 运行时获取bean(ApplicationContextAware接口)
- 基于Spring DM管理的Bundle获取Spring上下文对象及指定Bean对象
- 在完全由Spring管理的环境中使用Spring的Context获取Bean实例
- Spring ApplicationContextAware 获取bean
- Spring 的上下文Context对象获取
- ApplicationContextAware获取Spring上下文,通过基类获取properties中的配置属性
- 【Spring学习笔记-3.1】让bean获取spring容器上下文(applicationContext.xml)
- 在程序中用new ClassPathXmlApplicationContext()获取Spring的上下文环境注意事项
- spring获取从context中获取bean失败的解决方案
- ApplicationContextAware 获取Spring 上下文(Context)