文章目录
- 简介
- 源码分析
- 示例代码
- 示例一:扩展点的执行顺序
- 运行示例一
- 示例二:获取配置文件值
- 配置文件application.properties内容
- 定义工具类ConfigUtil
- controller测试调用
- 运行示例二
- 示例三:实现ResourceLoaderAware读取文件
- ExtendResourceLoaderAware 文件内容
- token.json 文件
- controller测试代码
- 运行示例三
简介
spring容器中Bean的生命周期内所有可扩展的点的调用顺序扩展接口 | 实现接口 |
---|---|
ApplicationContextlnitializer | initialize |
AbstractApplicationContext | refreshe |
BeanDefinitionRegistryPostProcessor | postProcessBeanDefinitionRegistry |
BeanDefinitionRegistryPostProcessor | postProcessBeanFactory |
BeanFactoryPostProcessor | postProcessBeanFactory |
instantiationAwareBeanPostProcessor | postProcessBeforelnstantiation |
SmartlnstantiationAwareBeanPostProcessor | determineCandidateConstructors |
MergedBeanDefinitionPostProcessor | postProcessMergedBeanDefinition |
InstantiationAwareBeanPostProcessor | postProcessAfterlnstantiation |
SmartInstantiationAwareBeanPostProcessor | getEarlyBeanReference |
BeanNameAware | setBeanName |
BeanFactoryAware | postProcessPropertyValues |
ApplicationContextAwareProcessor | invokeAwarelnterfaces |
InstantiationAwareBeanPostProcessor | postProcessBeforelnstantiation |
@PostConstruct | |
InitializingBean | afterPropertiesSet |
FactoryBean | getobject |
SmartlnitializingSingleton | afterSingletonslnstantiated |
CommandLineRunner | run |
DisposableBean | destroy |
- EnvironmentAware
- EmbeddedValueResolverAware
- ResourceLoaderAware
- ApplicationEventPublisherAware
- MessageSourceAware
- ApplicationStartupAware
- ApplicationContextAware
这些内部扩展点触发的时机在bean实例化之后,初始化之前。
1、EnvironmentAware
:凡注册到Spring容器内的bean,实现了EnvironmentAware接口重写setEnvironment方法后,在工程启动时可以获得application.properties的配置文件配置的属性值。
2、EmbeddedValueResolverAware
:用于获取StringValueResolver的一个扩展类, StringValueResolver用于获取基于String类型的properties的变量
3、ResourceLoaderAware
:用于获取ResourceLoader的一个扩展类,ResourceLoader可以用于获取classpath内所有的资源对象,可以扩展此类来拿到ResourceLoader对象。
4、ApplicationEventPublisherAware
:用于获取ApplicationEventPublisher的一个扩展类,ApplicationEventPublisher可以用来发布事件,结合ApplicationListener来共同使用
5、MessageSourceAware
:用于获取MessageSource的一个扩展类,MessageSource主要用来做国际化
6、ApplicationStartupAware
:要开始收集定制的StartupStep,组件可以实现ApplicationStartupAware接口直接获得ApplicationStartup实例或者在注入点请求ApplicationStartup类型。
7、ApplicationContextAware
:可以用来获取ApplicationContext的一个扩展类,也就是spring上下文管理器,可以手动的获取任何在spring上下文注册的bean
源码分析
从下列源码的invokeAwareInterfaces
方法可知,ApplicationContextAwareProcessor
关联了大部分Spring内置Aware接口,它们的执行顺序如
下源码码所示从上到下,最开始是EnvironmentAware,最后是ApplicationContextAware
package org.springframework.context.support;class ApplicationContextAwareProcessor implements BeanPostProcessor {private final ConfigurableApplicationContext applicationContext;private final StringValueResolver embeddedValueResolver;/*** Create a new ApplicationContextAwareProcessor for the given context.*/public ApplicationContextAwareProcessor(ConfigurableApplicationContext applicationContext) {this.applicationContext = applicationContext;this.embeddedValueResolver = new EmbeddedValueResolver(applicationContext.getBeanFactory());}@Override@Nullablepublic Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {if (!(bean instanceof EnvironmentAware || bean instanceof EmbeddedValueResolverAware ||bean instanceof ResourceLoaderAware || bean instanceof ApplicationEventPublisherAware ||bean instanceof MessageSourceAware || bean instanceof ApplicationContextAware ||bean instanceof ApplicationStartupAware)) {return bean;}AccessControlContext acc = null;if (System.getSecurityManager() != null) {acc = this.applicationContext.getBeanFactory().getAccessControlContext();}if (acc != null) {AccessController.doPrivileged((PrivilegedAction<Object>) () -> {invokeAwareInterfaces(bean);return null;}, acc);}else {invokeAwareInterfaces(bean);}return bean;}private void invokeAwareInterfaces(Object bean) {if (bean instanceof EnvironmentAware) {((EnvironmentAware) bean).setEnvironment(this.applicationContext.getEnvironment());}if (bean instanceof EmbeddedValueResolverAware) {((EmbeddedValueResolverAware) bean).setEmbeddedValueResolver(this.embeddedValueResolver);}if (bean instanceof ResourceLoaderAware) {((ResourceLoaderAware) bean).setResourceLoader(this.applicationContext);}if (bean instanceof ApplicationEventPublisherAware) {((ApplicationEventPublisherAware) bean).setApplicationEventPublisher(this.applicationContext);}if (bean instanceof MessageSourceAware) {((MessageSourceAware) bean).setMessageSource(this.applicationContext);}if (bean instanceof ApplicationStartupAware) {((ApplicationStartupAware) bean).setApplicationStartup(this.applicationContext.getApplicationStartup());}if (bean instanceof ApplicationContextAware) {((ApplicationContextAware) bean).setApplicationContext(this.applicationContext);}}
}
示例代码
示例一:扩展点的执行顺序
示例一展示的是7个内部扩展点所执行的顺序
@Slf4j
@Configuration
public class ExtendInvokeAware implements EnvironmentAware, EmbeddedValueResolverAware, ResourceLoaderAware,ApplicationEventPublisherAware, MessageSourceAware, ApplicationStartupAware, ApplicationContextAware, BeanNameAware {@Overridepublic void setApplicationContext(ApplicationContext applicationContext) throws BeansException {log.info("setApplicationContext--Extend--run {}",applicationContext);}@Overridepublic void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {log.info("setApplicationEventPublisher--Extend--run {}",applicationEventPublisher);}@Overridepublic void setApplicationStartup(ApplicationStartup applicationStartup) {log.info("setApplicationStartup--Extend--run {}",applicationStartup);}@Overridepublic void setEmbeddedValueResolver(StringValueResolver resolver) {log.info("setEmbeddedValueResolver--Extend--run {}",resolver);}@Overridepublic void setEnvironment(Environment environment) {log.info("setEnvironment--Extend--run {}",environment);}@Overridepublic void setMessageSource(MessageSource messageSource) {log.info("setMessageSource--Extend--run {}",messageSource);}@Overridepublic void setResourceLoader(ResourceLoader resourceLoader) {log.info("setResourceLoader--Extend--run {}",resourceLoader);}@Overridepublic void setBeanName(String name) {log.info("setBeanName--Extend--run {}",name);}
}
运行示例一
示例二:获取配置文件值
展示如何利用实现EmbeddedValueResolverAware来获取配置文件的属性值
配置文件application.properties内容
db.user=navicat
db.password=navicat
db.driverClass=com.mysql.jdbc.Driver
定义工具类ConfigUtil
该工具类功能为传入的key获取对应value
@Component
public class ConfigUtil implements EmbeddedValueResolverAware {private StringValueResolver resolver;@Overridepublic void setEmbeddedValueResolver(StringValueResolver resolver) {this.resolver = resolver;}/*** 获取属性,直接传入属性名称即可* @param key* @return*/public String getPropertiesValue(String key) {StringBuilder name = new StringBuilder("${").append(key).append("}");return resolver.resolveStringValue(name.toString());}}
controller测试调用
@GetMapping("/testConfig")
public void testConfig() {String s = configUtil.getPropertiesValue("db.user");System.out.println(s);
}
运行示例二
示例三:实现ResourceLoaderAware读取文件
ExtendResourceLoaderAware 文件内容
实现ResourceLoaderAware 接口,并读取文件内容进行打印
@Slf4j
@Configuration
public class ExtendResourceLoaderAware implements ResourceLoaderAware {private ResourceLoader resourceLoader;@Overridepublic void setResourceLoader(ResourceLoader resourceLoader) {this.resourceLoader = resourceLoader;log.info("ApplicationContextAware--Extend--run {}",resourceLoader);}public void showResourceData() throws IOException{//This line will be changed for all versions of other examplesResource banner = resourceLoader.getResource("file:d:/token.json");InputStream in = banner.getInputStream();BufferedReader reader = new BufferedReader(new InputStreamReader(in));while (true) {String line = reader.readLine();if (line == null)break;System.out.println(line);}reader.close();}
}
token.json 文件
{"name":"张三"}
controller测试代码
@Autowired
ApplicationContext context;@SuppressWarnings("resource")
@GetMapping("/testResource")
public void testResource() throws Exception{ExtendResourceLoaderAware extendResourceLoaderAware = (ExtendResourceLoaderAware) context.getBean("extendResourceLoaderAware");extendResourceLoaderAware.showResourceData();
}