Aware
在Spring當中有一些內置的對象是未開放給我們使用的,例如Spring的上下文ApplicationContext、環境屬性Environment,BeanFactory等等其他的一些內置對象,而在我們可以通過實現對應的Aware接口去拿到我們想要的一些屬性,一般命名都是xxxAware,在創建對象的時候, 會調用接口規定的方法注入到相關組件:Aware
常用的Aware:
用法示例:
源碼解析
我們先了解什么是BeanPostProcessor,是在創建Bean之前以及創建Bean之后的一種后置處理器,這里就簡單的講一下這個,就是在我們使用的這些注解,例如:@Async (異步執行),@Bean,@Component、@Autowired、@PropertySource等等都需要經過BeanPostProcessor去處理才能加載到容器當中,
先看一個示例:
不僅僅有BeanPostProcessor還有BeanDefinitionRegistryPostProcessor(Bean注冊器后置處理器)、BeanFactoryPostProcessor(BeanFactory后置處理器),
在處理Aware實現類的時候就會有對應的一個AwareProcessor去處理,我們拿ApplicationContextAware做示例:
我們找到對應的后置處理器ApplicationContextAwareProcessor
因為BeanPostProcessor有兩個接口實現,但是只對處理前做內置對象賦值,將對應的對象暴露給我們
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(final Object bean, String beanName) throws BeansException {AccessControlContext acc = null;if (System.getSecurityManager() != null &&(bean instanceof EnvironmentAware || bean instanceof EmbeddedValueResolverAware ||bean instanceof ResourceLoaderAware || bean instanceof ApplicationEventPublisherAware ||bean instanceof MessageSourceAware || bean instanceof ApplicationContextAware)) {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 Aware) {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 ApplicationContextAware) {((ApplicationContextAware) bean).setApplicationContext(this.applicationContext);}}}@Overridepublic Object postProcessAfterInitialization(Object bean, String beanName) {return bean;}}
不得不說Spring的這種設計還是很厲害的,建議可以買本Spring IOC源碼分析的書看看比較好,了解的更加細致
?