浅析Spring IoC源码(八)了解BeanFactoryAware

 2019-11-02 21:23  阅读(1153)
文章分类:Spring boot

这一节我们还是先了解一下BeanFactoryAware这个接口,之所以说只是了解一下,还是希望等到分析refresh()的时候有个更好的理解吧

照旧先上源代码:

20191102100767\_1.png

官方解释:实现这个接口的bean其实是希望知道自己属于哪一个beanfactory

言简意赅,不需要做多解释,先实现一下自己,看看他的基本功能吧,看代码:

MyBeanFactoryAware.java

[java]
view plain
copy

  1. package org.study.spring.beanfactoryaware;
  2. import org.springframework.beans.BeansException;
  3. import org.springframework.beans.factory.BeanFactory;
  4. import org.springframework.beans.factory.BeanFactoryAware;
  5. **public****class MyBeanFactoryAware implements** BeanFactoryAware{
  6. **public****void setBeanFactory(BeanFactory beanFactory) throws** BeansException {
  7. System.out.println(“I belong to :”+beanFactory);
  8. }
  9. }

bean-factory-aware.xml

[html]
view plain
copy

  1. ****
  2. **<****beans**xmlns=“http://www.springframework.org/schema/beans
  3. xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance”xmlns:context=“http://www.springframework.org/schema/context
  4. xmlns:mybatis-spring=“http://mybatis.org/schema/mybatis-spring
  5. xmlns:tx=“http://www.springframework.org/schema/tx”xmlns:jee=“http://www.springframework.org/schema/jee
  6. xsi:schemaLocation=”http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
  7. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
  8. http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
  9. http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.xsd
  10. http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd>
  11. <**beanid=“mybeanFactoryAware”class=“org.study.spring.beanfactoryaware.MyBeanFactoryAware”></bean**>
  12. </**beans**>

MyBeanFactoryAwareTest.java

[java]
view plain
copy

  1. package org.study.spring.beanfactoryaware;
  2. import org.junit.Test;
  3. import org.springframework.context.ApplicationContext;
  4. import org.springframework.context.support.ClassPathXmlApplicationContext;
  5. **public****class** MyBeanFactoryAwareTest{
  6. @Test
  7. **public****void test2() throws** Exception{
  8. ApplicationContext applicationContext = new ClassPathXmlApplicationContext(“bean-factory-aware.xml”);
  9. MyBeanFactoryAware mybeanFactoryAware = applicationContext.getBean(“mybeanFactoryAware”,MyBeanFactoryAware.class);
  10. }
  11. }

运行结果:

20191102100767\_2.png

的确,根据我们上次分析的源代码,的确属于DefaultListableBeanFactory

换个说法,我们目前不知道这个接口更多真实的意义,如果不分析其他的部分,我们就知道可以在实现BeanFactoryAware的bean中获取beanfactory,也就是获取上下文,其他的不知道暂时有什么用处,也许分析refresh就会有理解了吧~


来源:http://ddrv.cn

点赞(0)
版权归原创作者所有,任何形式转载请联系作者; Java 技术驿站 >> 浅析Spring IoC源码(八)了解BeanFactoryAware

相关推荐