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"})
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· DeepSeek在M芯片Mac上本地化部署