一.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);