spring中自定义组件需要使用spring的底层组件时,可以通过自定义组件实现相关XxxAware接口,重写其中的方法进而实现
例如:自定义一个组件,该组件中需要使用ApplicationContext、BeanFactory,那么我们就可以通过实现ApplicationContextAware、BeanFactoryAware接口实现
ApplicationContextAware
public class MyAware implements ApplicationContextAware { private ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { System.out.println("传入的IOC容器applicationContext = [" + applicationContext + "]"); this.applicationContext = applicationContext; } } @Configuration public class AwareConfig { @Bean public MyAware myAware(){ return new MyAware(); } } public class TestAware { @Test public void testM(){ ApplicationContext context = new AnnotationConfigApplicationContext(AwareConfig.class); System.out.println("context = " + context); } }
结果 传入的IOC容器applicationContext = [org.spring[email protected]2ff5659e: startup date [Wed May 29 14:00:42 GMT+08:00 2019]; root of context hierarchy] context = org.spring[email protected]2ff5659e: startup date [Wed May 29 14:00:42 GMT+08:00 2019]; root of context hierarchy
BeanNameAware
public class MyAware implements BeanNameAware{ @Override public void setBeanName(String name) { System.out.println("name = [" + name + "]"); } }
结果 name = [myAware] context = org.spring[email protected]2ff5659e: startup date [Wed May 29 14:07:16 GMT+08:00 2019]; root of context hierarchy
EmbeddedValueResolverAware
public class MyAware implements EmbeddedValueResolverAware{ @Override public void setEmbeddedValueResolver(StringValueResolver stringValueResolver) { String value = stringValueResolver.resolveStringValue("当前操作系统:${os.name},10-9=#{10-9}"); System.out.println("value = " + value); } }
结果 value = 当前操作系统:Windows 10,10-9=1 context = org.spring[email protected]2ff5659e: startup date [Wed May 29 14:13:11 GMT+08:00 2019]; root of context hierarchy
其它XxxAware用法类似
通过Aware可以把spring底层组件注入到自定义的bean中,再用相应的processor处理器处理
ApplicationContextAware是利用ApplicationContextAwareProcessor来处理的,XxxAware也有相应的processor进行处理,其实就是相关后置处理器完成处理工作
原文地址:https://www.cnblogs.com/qf123/p/10943514.html
时间: 2024-10-01 04:33:34