1. 这个接口有什么用
org.springframework.context.ApplicationContextAware,简单点说,就是当一个类实现了这个接口ApplicationContext中的所有bean,也就是可以获取Sping配置文件里所有的Bean。
2. 用法流程
很容易。
(1)写个类实现org.springframework.context.ApplicationContextAware,当做工具类就好。
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class SpringContextUtil implements ApplicationContextAware {
// Spring应用上下文环境
private static ApplicationContext applicationContext;
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringContextUtil.applicationContext = applicationContext;
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
public static Object getBean(String name) throws BeansException {
return applicationContext.getBean(name);
}
}
(2)让spring配置文件里管理你创建的那个类(我的spring配置文件是servlet-context.xml,别问我为什么叫这么个名字,用Spring Tool Suites这个IDE生成的)
<!-- 项目里获取Spring配置文件里所有Bean的工具类 -->
<beans:bean id="SpringContextUtilC" class="com.onezg.myapp.util.sys.SpringContextUtil"/>
(3) 使用
IAssetService service =(IAssetService) SpringContextUtilC.getBean("assetServiceImpl");