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"})
posted @   懦尘  阅读(347)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· DeepSeek在M芯片Mac上本地化部署
点击右上角即可分享
微信分享提示