这一节我们还是先了解一下BeanFactoryAware这个接口,之所以说只是了解一下,还是希望等到分析refresh()的时候有个更好的理解吧
照旧先上源代码:
官方解释:实现这个接口的bean其实是希望知道自己属于哪一个beanfactory
言简意赅,不需要做多解释,先实现一下自己,看看他的基本功能吧,看代码:
MyBeanFactoryAware.java
package org.study.spring.beanfactoryaware;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
public class MyBeanFactoryAware implements BeanFactoryAware{
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
System.out.println("I belong to :"+beanFactory);
}
}
bean-factory-aware.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
<bean id="mybeanFactoryAware" class="org.study.spring.beanfactoryaware.MyBeanFactoryAware"></bean>
</beans>
MyBeanFactoryAwareTest.java
package org.study.spring.beanfactoryaware;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyBeanFactoryAwareTest{
@Test
public void test2() throws Exception{
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean-factory-aware.xml");
MyBeanFactoryAware mybeanFactoryAware = applicationContext.getBean("mybeanFactoryAware",MyBeanFactoryAware.class);
}
}
运行结果:
的确,根据我们上次分析的源代码,的确属于DefaultListableBeanFactory
换个说法,我们目前不知道这个接口更多真实的意义,如果不分析其他的部分,我们就知道可以在实现BeanFactoryAware的bean中获取beanfactory,也就是获取上下文,其他的不知道暂时有什么用处,也许分析refresh就会有理解了吧~