ApplicationContextAware获取IOC容器
目录
常见Aware实现
接口 | 作用 |
---|---|
ApplicationContextAware | 获取当前应用的上下文对象 |
EnvironmentAware | 获取环境变量,包括我们配置的以及系统的 |
ApplicationEventPublisherAware | 获取应用事件发布器,可以发布我们监听的事件 |
BeanNameAware | 获取容器中的bean的名称 |
BeanClassLoaderAware | 获取bean的类加载器 |
BeanFactoryAware | 获取bean的创建工厂对象,如果我们要创建,可以试试通过他来创建 |
EmbeddedValueResolverAware | 获取spring容器加载的properties文件属性值 |
ResourceLoaderAware | 获取资源加载器,我们要加载自己的资源,可以使用他 |
MessageSourceAware | 获取文本信息 ,解析消息 |
ApplicationContextAware作用
1、ApplicationContext是什么?
ApplicationContext
是我们常用的IOC容器,而他的顶层接口便是BeanFactory
,ApplicationContext
对BeanFactory
做了拓展,功能更加强大。
2、ApplicationContextAware作用
获取IOC容器有三种方式,就是使用ApplicationContext
接口下的三个实现类:
ClassPathXmlApplicationContext
FileSystemXmlApplicationContext
AnnotationConfigApplicationContext
SpringBoot通过回调的方式,将其资源传递给用户,ApplicationContextAware
接口用来获取框架自动初始化的ioc容器对象。
public interface ApplicationContextAware extends Aware { void setApplicationContext(ApplicationContext applicationContext) throws BeansException; }
ApplicationContextAware使用
1、编写一个类,实现ApplicationContextAware
接口,并且覆盖其方法
2、定义一个内部成员保存IOC容器,后面需要用的时候直接获取
import lombok.extern.slf4j.Slf4j; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; @Component @Slf4j public class MyApplicationContextAware implements ApplicationContextAware { // 定义静态ApplicationContext private static ApplicationContext applicationContext = null; /** * 重写接口的方法,springboot会回调这个函数,该方法的参数为框架自动加载的IOC容器对象 * 该方法在启动项目的时候会自动执行,前提是该类上有IOC相关注解,例如@Component * * @param applicationContext IOC容器applicationContext * @throws BeansException */ @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { // 将框架加载的ioc赋值给全局静态ioc MyApplicationContextAware.applicationContext = applicationContext; log.info("ApplicationContext init successfully"); } /** * 获取applicationContext */ public static ApplicationContext getApplicationContext() { return applicationContext; } /** * 通过name获取 Bean */ public static Object getBean(String name) { return getApplicationContext().getBean(name); } /** * 通过class获取Bean */ public static <T> T getBean(Class<T> clazz) { return getApplicationContext().getBean(clazz); } /** * 通过name,以及Clazz返回指定的Bean */ public static <T> T getBean(String name, Class<T> clazz) { return getApplicationContext().getBean(name, clazz); } }
本文来自博客园,作者:Lz_蚂蚱,转载请注明原文链接:https://www.cnblogs.com/leizia/p/18240469
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步