ApplicationContextAware 接口
有何作用
当一个类实现了这个接口之后,这个类就可以方便地获得 ApplicationContext 中的所有 bean。
如何使用
步骤
1、定义一个工具类,实现接口,实现 setApplicationContext 方法
2、注册该工具类
目的是让 Spring 知道这个工具类,因为 Spring 能够为我们自动地执行 setApplicationContext 方法。
3、使用工具类获取 Bean
SpringBoot Demo
pom 依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.6.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
SpringContextUtil
@Component
public class SpringContextUtil implements ApplicationContextAware{
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
System.out.println("applicationContext正在初始化,application:"+applicationContext);
SpringContextUtil.applicationContext = applicationContext;
}
public static Object getBean(String name) {
return applicationContext.getBean(name);
}
@SuppressWarnings("unchecked")
public static <T>T getBeanT(String name) {
return (T)applicationContext.getBean(name);
}
public static <T>T getBean(Class<T> clazz){
return applicationContext.getBean(clazz);
}
}
Contoller
@RequestMapping("s1")
@ResponseBody
public void save1() {
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
userService = (UserService)app.getBean("userService");
userService.save();
}
@RequestMapping("s2")
@ResponseBody
public void save2() {
userService = SpringContextUtil.getBeanT("userService");
userService.save();
}
启动类
使用配置文件的情况,别忘记加载
@ImportResource(locations= {"classpath:applicationContext.xml"})