Springcloud学习笔记52--通过ApplicationContextAware接口从spring上下文中获取到需要的bean(获取spring托管的Bean)
1.背景
在spring项目中,bean之间的依赖关系是 spring容器自动管理的,但是一个项目中有些类不在spring容器中却需要使用spring管理的bean,这时候不能通过正常的方式(注解等方式)注入bean,在spring中提供了ApplicationContextAware接口,通过ApplicationContextAware接口可以获取到spring上下文,从而从spring上下文中获取到需要的bean。
2 ApplicationContext 通过 getBean方法
详细介绍Spring容器 ApplicationContext 通过 getBean方法 获取实例的几种方式;
3.SpringUtils.java
我们可以编写一个工具类来实现ApplicationContextAware,通过工具类来获取我们需要的bean在spring容器外的类调用bean的方法,具体代码如下:
import org.springframework.beans.BeansException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; //此处使用注解的方式把工具类加入到容器中,可以使用xml,配置类等方式,必须要加入到容器中 @Component public class SpringUtils implements ApplicationContextAware { private static ApplicationContext applicationContext; //此方法是父类ApplicationContextAware 中的方法 重写 @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { if(SpringUtils.applicationContext == null){ SpringUtils.applicationContext = applicationContext; } } public static ApplicationContext getApplicationContext() { return applicationContext; } public static Object getBean(String name){ return getApplicationContext().getBean(name); } public static <T> T getBean(Class<T> clazz){ return getApplicationContext().getBean(clazz); } public static <T> T getBean(String name,Class<T> clazz){ return getApplicationContext().getBean(name, clazz); } }
容器外类 TestAppContext.java
public class TestAppContext{ //因为Person是容器中的bean TestAppContext不受spring容器管理 所以 //这里不能通过正常的方式注入 private Person person; public String getPersonName(){ //通过bean的名称来获取bean person = (Person)SpringUtils.getBean("person");
person2 = (Person)SpringUtils.getBean(Person.class);
return person.getName(); }
}
参考文献:https://blog.csdn.net/qq_28070019/article/details/83624380
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程
· .NET 10 首个预览版发布,跨平台开发与性能全面提升
· 《HelloGitHub》第 107 期
· 全程使用 AI 从 0 到 1 写了个小工具
· 从文本到图像:SSE 如何助力 AI 内容实时呈现?(Typescript篇)
2021-11-22 Linux学习笔记05---linux 常用操作命令02(touch命令、cp命令、rm命令、mv命令、df命令)
2021-11-22 Java基础知识13--Java反射原理以及基本使用和重写与重载的区别