-
在 spring 中提供了很多关于 Aware 的接口,该接口拥有一个统一的规律,即在 spring 对实现了 Aware 相关接口 bean 的初始化时,同时会注入相关的资源。例如:实现了 BeanFactoryAware 接口的 bean 在初始化完成后,容器会自动注入 BeanFactory 实例;实现了 ApplicationContextAware 接口的 bean 在初始化后,也会同样注入 ApplicationContext 实例。
-
示例代码:
/** * 实现Aware相关接口的bean */ public class AwareTest implements BeanFactoryAware { private BeanFactory beanFactory; /** * spring通过set方法注入beanFactory实例 * @param beanFactory * @throws BeansException */ @Override public void setBeanFactory(BeanFactory beanFactory) throws BeansException { this.beanFactory = beanFactory; } /** * 测试方法 */ public void awareSay() { Hello hello = (Hello) beanFactory.getBean("hello"); hello.say(); } }
/** * 测试实例 */ public class Hello { public void say() { System.out.println("hello aware"); } }
/** * 运行测试 */ public class Run { public static void main(String[] args) { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-bean.xml"); AwareTest testAware = (AwareTest) applicationContext.getBean("test_aware"); testAware.awareSay(); } }
配置文件
<bean id="test_aware" class="com.source.aware.AwareTest" /> <bean id="hello" class="com.source.aware.Hello" />
在实现 Aware 接口后,通过 spring 自动注入 BeanFactory 的实例就可以获取所有 spring 管理的 bean,其他相关接口也有类似的规律。
- 最后我们看看 spring 源码中是怎样去实现这一功能的。AbstractAutowireCapableBeanFactory.java
private void invokeAwareMethods(final String beanName, final Object bean) { if (bean instanceof Aware) { if (bean instanceof BeanNameAware) { ((BeanNameAware) bean).setBeanName(beanName); } if (bean instanceof BeanClassLoaderAware) { ClassLoader bcl = getBeanClassLoader(); if (bcl != null) { ((BeanClassLoaderAware) bean).setBeanClassLoader(bcl); } } //spring通过类型判断后,调用set方法为实现了BeanFactoryAware接口的bean注入AbstractAutowireCapableBeanFactory实例 if (bean instanceof BeanFactoryAware) { ((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this); } } }
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于