测试代码
package com.common.utils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class SpringContextHolder implements ApplicationContextAware{
private static ApplicationContext context = null;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringContextHolder.context = applicationContext;
System.out.println((applicationContext==null) + "-----------");
}
/**
* 取得存储在静态变量中的ApplicationContext.
*/
public ApplicationContext getApplicationContext(){
return context;
}
public static <T> T getBean(String name) {
return (T) context.getBean(name);
}
public static <T> T getBean(Class<T> requiredType) {
return context.getBean(requiredType);
}
}
1.实现ApplicationAware接口中的方法,通过注入来设置ApplicationContext
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<display-name>test</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:/application.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
1.读取classpath下面的application.xml配置文件
application.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<description>Spring Configuration</description>
<bean id="springContextHolder" class="com.common.utils.SpringContextHolder"/>
</beans>
1.启动Tomcat,输出false———–,成功注入
2.这样就可以在任何地方取出ApplicationContext来使用
3.通过调用SpringContextHolder.getBean方法来取出对象使用
4.这里注意application.xml放的位置,我放在test/resource目录下,test是project名,也就是classpath下面,在web.xml中有指定读取位置
当然也可以不用写bean直接在application.xml中使用标签context:component-scan进行扫描,并在SpringContextHolder的类名上面标注上@Service