Spring源码解析:BeanFactory深入理解

(现在一般都用ApplicantContext代替BeanFactory)

说到Spring框架,人们往往大谈特谈一些似乎高逼格的东西,比如依赖注入,控制反转,面向切面等等。但是却忘记了最基本的一点,Spring的本质是一个bean工厂(beanFactory)或者说bean容器,它按照我们的要求,生产我们需要的各种各样的bean,提供给我们使用。只是在生产bean的过程中,需要解决bean之间的依赖问题,才引入了依赖注入(DI)这种技术。也就是说依赖注入是beanFactory生产bean时为了解决bean之间的依赖的一种技术而已。

那么我们为什么需要Spring框架来给我们提供这个beanFactory的功能呢?原因是一般我们认为是,可以将原来硬编码的依赖,通过Spring这个beanFactory这个工厂来注入依赖,也就是说原来只有依赖方和被依赖方,现在我们引入了第三方——spring这个beanFactory,由它来解决bean之间的依赖问题,达到了松耦合的效果;这个只是原因之一,还有一个更加重要的原因:在没有spring这个beanFactory之前,我们都是直接通过new来实例化各种对象,现在各种对象bean的生产都是通过beanFactory来实例化的,这样的话,spring这个beanFactory就可以在实例化bean的过程中,做一些小动作——在实例化bean的各个阶段进行一些额外的处理,也就是说beanFactory会在bean的生命周期的各个阶段中对bean进行各种管理,并且spring将这些阶段通过各种接口暴露给我们,让我们可以对bean进行各种处理,我们只要让bean实现对应的接口,那么spring就会在bean的生命周期调用我们实现的接口来处理该bean。下面我们看是如何实现这一点的。

1. bean容器的启动

bean在实例化之前,必须是在bean容器启动之后。所以就有了两个阶段:

1)bean容器的启动阶段;

2)容器中bean的实例化阶段;

在启动阶段

1> 首先是读取bean的xml配置文件,然后解析xml文件中的各种bean的定义,将xml文件中的每一个<bean />元素分别转换成一个BeanDefinition对象,其中保存了从配置文件中读取到的该bean的各种信息:

 
  1. public abstract class AbstractBeanDefinition extends BeanMetadataAttributeAccessor

  2. implements BeanDefinition, Cloneable {

  3. private volatile Object beanClass;

  4. private String scope = SCOPE_DEFAULT;

  5. private boolean abstractFlag = false;

  6. private boolean lazyInit = false;

  7. private int autowireMode = AUTOWIRE_NO;

  8. private int dependencyCheck = DEPENDENCY_CHECK_NONE;

  9. private String[] dependsOn;

  10. private ConstructorArgumentValues constructorArgumentValues;

  11. private MutablePropertyValues propertyValues;

  12. private String factoryBeanName;

  13. private String factoryMethodName;

  14. private String initMethodName;

  15. private String destroyMethodName;

  16. }

beanClass保存bean的class属性,scop保存bean是否单例,abstractFlag保存该bean是否抽象,lazyInit保存是否延迟初始化,autowireMode保存是否自动装配,dependencyCheck保存是否坚持依赖,dependsOn保存该bean依赖于哪些bean(这些bean必须提取初始化),constructorArgumentValues保存通过构造函数注入的依赖,propertyValues保存通过setter方法注入的依赖,factoryBeanName和factoryMethodName用于factorybean,也就是工厂类型的bean,initMethodName和destroyMethodName分别对应bean的init-method和destory-method属性,比如:

 
  1. <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource"

  2. init-method="init" destroy-method="close">

读完配置文件之后,得到了很多的BeanDefinition对象,

2> 然后通过BeanDefinitionRegistry将这些bean注册到beanFactory中:

 
  1. public interface BeanDefinitionRegistry extends AliasRegistry {

  2. void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)throws

  3. BeanDefinitionStoreException;

  4. void removeBeanDefinition(String beanName) throws NoSuchBeanDefinitionException;

  5. BeanDefinition getBeanDefinition(String beanName) throws NoSuchBeanDefinitionException;

  6. boolean containsBeanDefinition(String beanName);

  7. String[] getBeanDefinitionNames();

  8. int getBeanDefinitionCount();

  9. boolean isBeanNameInUse(String beanName);

  10. }

BeanFactory的实现类,需要实现BeanDefinitionRegistry 接口:

 
  1. @SuppressWarnings("serial")

  2. public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory

  3. implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {

  4. /** Map of bean definition objects, keyed by bean name */

  5. private final Map<String, BeanDefinition> beanDefinitionMap = new

  6. ConcurrentHashMap<String, BeanDefinition>(64);

  7. @Override

  8. public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)

  9. throws BeanDefinitionStoreException {

  10. // ... ...

  11. this.beanDefinitionMap.put(beanName, beanDefinition);

  12. // ... ...

  13. }

  14. }

我们看到BeanDefinition被注册到了 DefaultListableBeanFactory, 保存在它的一个ConcurrentHashMap中。

将BeanDefinition注册到了beanFactory之后,在这里Spring为我们提供了一个扩展的切口,允许我们通过实现接口BeanFactoryPostProcessor 在此处来插入我们定义的代码:

 
  1. public interface BeanFactoryPostProcessor {

  2. /**

  3. * Modify the application context's internal bean factory after its standard

  4. * initialization. All bean definitions will have been loaded, but no beans

  5. * will have been instantiated yet. This allows for overriding or adding

  6. * properties even to eager-initializing beans.

  7. * @param beanFactory the bean factory used by the application context

  8. * @throws org.springframework.beans.BeansException in case of errors

  9. */

  10. void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws

  11. BeansException;

  12. }

典型的例子就是:PropertyPlaceholderConfigurer,我们一般在配置数据库的dataSource时使用到的占位符的值,就是它注入进去的:

 
  1. public abstract class PropertyResourceConfigurer extends PropertiesLoaderSupport

  2. implements BeanFactoryPostProcessor, PriorityOrdered {

  3. @Override

  4. public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws

  5. BeansException {

  6. try {

  7. Properties mergedProps = mergeProperties();

  8. // Convert the merged properties, if necessary.

  9. convertProperties(mergedProps);

  10. // Let the subclass process the properties.

  11. processProperties(beanFactory, mergedProps);

  12. }

  13. catch (IOException ex) {

  14. throw new BeanInitializationException("Could not load properties", ex);

  15. }

  16. }

  17. }

processProperties(beanFactory, mergedProps);在子类中实现的,功能就是将 ${jdbc_username}等等这些替换成实际值。

 
  1. <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource"

  2. init-method="init" destroy-method="close">

  3. <property name="url" value="${jdbc_url}" />

  4. <property name="username" value="${jdbc_username}" />

  5. <property name="password" value="${jdbc_password}" />

  6. </bean>

 

2、bean的实例化阶段

实例化阶段主要是通过反射或者CGLIB对bean进行实例化,在这个阶段Spring又给我们暴露了很多的扩展点:

1> 各种的Aware接口,比如 BeanFactoryAware,MessageSourceAware,ApplicationContextAware

对于实现了这些Aware接口的bean,在实例化bean时Spring会帮我们注入对应的:BeanFactory, MessageSource,ApplicationContext的实例:

 
  1. public interface BeanFactoryAware extends Aware {

  2. /**

  3. * Callback that supplies the owning factory to a bean instance.

  4. * <p>Invoked after the population of normal bean properties

  5. * but before an initialization callback such as

  6. * {@link InitializingBean#afterPropertiesSet()} or a custom init-method.

  7. * @param beanFactory owning BeanFactory (never {@code null}).

  8. * The bean can immediately call methods on the factory.

  9. * @throws BeansException in case of initialization errors

  10. * @see BeanInitializationException

  11. */

  12. void setBeanFactory(BeanFactory beanFactory) throws BeansException;

  13. }

 
  1. public interface ApplicationContextAware extends Aware {

  2. /**

  3. * Set the ApplicationContext that this object runs in.

  4. * Normally this call will be used to initialize the object.

  5. * <p>Invoked after population of normal bean properties but before an init callback such

  6. * as {@link org.springframework.beans.factory.InitializingBean#afterPropertiesSet()}

  7. * or a custom init-method. Invoked after {@link ResourceLoaderAware#setResourceLoader},

  8. * {@link ApplicationEventPublisherAware#setApplicationEventPublisher} and

  9. * {@link MessageSourceAware}, if applicable.

  10. * @param applicationContext the ApplicationContext object to be used by this object

  11. * @throws ApplicationContextException in case of context initialization errors

  12. * @throws BeansException if thrown by application context methods

  13. * @see org.springframework.beans.factory.BeanInitializationException

  14. */

  15. void setApplicationContext(ApplicationContext applicationContext) throws BeansException;

  16. }

 
  1. public interface MessageSourceAware extends Aware {

  2. /**

  3. * Set the MessageSource that this object runs in.

  4. * <p>Invoked after population of normal bean properties but before an init

  5. * callback like InitializingBean's afterPropertiesSet or a custom init-method.

  6. * Invoked before ApplicationContextAware's setApplicationContext.

  7. * @param messageSource message sourceto be used by this object

  8. */

  9. void setMessageSource(MessageSource messageSource);

  10. }

2> BeanPostProcessor接口

实现了BeanPostProcessor接口的bean,在实例化bean时Spring会帮我们调用接口中的方法:

 
  1. public interface BeanPostProcessor {

  2. /**

  3. * Apply this BeanPostProcessor to the given new bean instance <i>before</i> any bean

  4. * initialization callbacks (like InitializingBean's {@code afterPropertiesSet}

  5. * or a custom init-method). The bean will already be populated with property values.

  6. * The returned bean instance may be a wrapper around the original.*/

  7. Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException;

  8. /**

  9. * Apply this BeanPostProcessor to the given new bean instance <i>after</i> any bean

  10. * initialization callbacks (like InitializingBean's {@code afterPropertiesSet}

  11. * or a custom init-method). The bean will already be populated with property values.

  12. * The returned bean instance may be a wrapper around the original.*/

  13. Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException;

  14. }

从注释中可以知道 postProcessBeforeInitialization方法在 InitializingBean接口的 afterPropertiesSet方法之前执行,而postProcessAfterInitialization方法在 InitializingBean接口的afterPropertiesSet方法之后执行。

3> InitializingBean接口

实现了InitializingBean接口的bean,在实例化bean时Spring会帮我们调用接口中的方法:

 
  1. public interface InitializingBean {

  2. /**

  3. * Invoked by a BeanFactory after it has set all bean properties supplied

  4. * (and satisfied BeanFactoryAware and ApplicationContextAware).

  5. * <p>This method allows the bean instance to perform initialization only

  6. * possible when all bean properties have been set and to throw an

  7. * exception in the event of misconfiguration.

  8. * @throws Exception in the event of misconfiguration (such

  9. * as failure to set an essential property) or if initialization fails.

  10. */

  11. void afterPropertiesSet() throws Exception;

  12. }

 4> DisposableBean接口

实现了BeanPostProcessor接口的bean,在该bean死亡时Spring会帮我们调用接口中的方法:

 
  1. public interface DisposableBean {

  2. /**

  3. * Invoked by a BeanFactory on destruction of a singleton.

  4. * @throws Exception in case of shutdown errors.

  5. * Exceptions will get logged but not rethrown to allow

  6. * other beans to release their resources too.

  7. */

  8. void destroy() throws Exception;

  9. }

 InitializingBean接口 和 DisposableBean接口对应于 <bean /> 的 init-method 和 destory-method 属性,其经典的例子就是dataSource:

<bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">

所以在Spring初始化 dataSource 这个bean之后会调用 DruidDataSource.init 方法:

 
  1. public void init() throws SQLException {

  2. // ... ...try {

  3. lock.lockInterruptibly();

  4. } catch (InterruptedException e) {

  5. throw new SQLException("interrupt", e);

  6. }

  7. boolean init = false;

  8. try {

  9. connections = new DruidConnectionHolder[maxActive];

  10. SQLException connectError = null;

  11. try {

  12. for (int i = 0, size = getInitialSize(); i < size; ++i) {

  13. Connection conn = createPhysicalConnection();

  14. DruidConnectionHolder holder = new DruidConnectionHolder(this, conn);

  15. connections[poolingCount++] = holder;

  16. }

  17. if (poolingCount > 0) {

  18. poolingPeak = poolingCount;

  19. poolingPeakTime = System.currentTimeMillis();

  20. }

  21. } catch (SQLException ex) {

  22. LOG.error("init datasource error", ex);

  23. connectError = ex;

  24. }

  25. } catch (SQLException e) {

  26. LOG.error("dataSource init error", e);

  27. throw e;

  28. } catch (InterruptedException e) {

  29. throw new SQLException(e.getMessage(), e);

  30. } finally {

  31. inited = true;

  32. lock.unlock();

  33. }

  34. }

基本就是初始化数据库连接池。

在dataSource 这个bean死亡时会调用 DruidDataSource.close()方法:

 
  1. public void close() {

  2. lock.lock();

  3. try {

  4. for (int i = 0; i < poolingCount; ++i) {

  5. try {

  6. DruidConnectionHolder connHolder = connections[i];

  7. for (PreparedStatementHolder stmtHolder :

  8. connHolder.getStatementPool().getMap().values()) {

  9. connHolder.getStatementPool().closeRemovedStatement(stmtHolder);

  10. }

  11. connHolder.getStatementPool().getMap().clear();

  12. Connection physicalConnection = connHolder.getConnection();

  13. physicalConnection.close();

  14. connections[i] = null;

  15. destroyCount.incrementAndGet();

  16. } catch (Exception ex) {

  17. LOG.warn("close connection error", ex);

  18. }

  19. }

  20. } finally {

  21. lock.unlock();

  22. }

  23. }

基本就是关闭连接池中的连接。

另外注解 @PostConstruct 和 @PreDestroy 也能达到 InitializingBean接口 和 DisposableBean接口的效果。

3、 总结

spring容器接管了bean的实例化,不仅仅是通过依赖注入达到了松耦合的效果,同时给我们提供了各种的扩展接口,来在bean的生命周期的各个时期插入我们自己的代码:

0)BeanFactoryPostProcessor接口(在容器启动阶段)

1)各种的Aware接口

2)BeanPostProcessor接口

3)InitializingBean接口(@PostConstruct, init-method)

4)DisposableBean接口(@PreDestroy, destory-method)

3. FactoryBean接口

实现了FactoryBean接口的bean是一类叫做factory的bean。其特点是,spring会在使用getBean()调用获得该bean时,会自动调用该bean的getObject()方法,所以返回的不是factory这个bean,而是这个bean.getOjbect()方法的返回值

 
  1. public interface FactoryBean<T> {

  2. T getObject() throws Exception;

  3. Class<?> getObjectType();

  4. boolean isSingleton();

  5. }

典型的例子有spring与mybatis的结合:

 
  1. <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">

  2. <property name="dataSource" ref="dataSource" />

  3. <property name="configLocation" value="classpath:config/mybatis-config-master.xml" />

  4. <property name="mapperLocations" value="classpath*:config/mappers/master/**/*.xml" />

  5. </bean>

我们看上面该bean,因为实现了FactoryBean接口,所以返回的不是 SqlSessionFactoryBean 的实例,而是它的 SqlSessionFactoryBean.getObject() 的返回值:

 
  1. public class SqlSessionFactoryBean implements FactoryBean<SqlSessionFactory>,

  2. InitializingBean, ApplicationListener<ApplicationEvent> {

  3. private static final Log logger = LogFactory.getLog(SqlSessionFactoryBean.class);

  4. private Resource configLocation;

  5. private Resource[] mapperLocations;

  6. private DataSource dataSource;

  7. public SqlSessionFactory getObject() throws Exception {

  8. if (this.sqlSessionFactory == null) {

  9. afterPropertiesSet();

  10. }

  11. return this.sqlSessionFactory;

  12. }

其实他是一个专门生产 sqlSessionFactory 的工厂,所以才叫 SqlSessionFactoryBean。 而SqlSessionFactory又是生产SqlSession的工厂。

还有spring与ibatis的结合:

 
  1. <!-- Spring提供的iBatis的SqlMap配置 -->

  2. <bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">

  3. <property name="configLocation" value="classpath:sqlmap/sqlmap-config.xml" />

  4. <property name="dataSource" ref="dataSource" />

  5. </bean>

 
  1. public class SqlMapClientFactoryBean implements FactoryBean<SqlMapClient>, InitializingBean {

  2. private Resource[] configLocations;

  3. private Resource[] mappingLocations;

  4. private Properties sqlMapClientProperties;

  5. private DataSource dataSource;

  6. private boolean useTransactionAwareDataSource = true;

  7. private Class transactionConfigClass = ExternalTransactionConfig.class;

  8. private Properties transactionConfigProperties;

  9. private LobHandler lobHandler;

  10. private SqlMapClient sqlMapClient;

  11. public SqlMapClient getObject() {

  12. return this.sqlMapClient;

  13. }

 

SqlMapClientFactoryBean 返回的是 getObject() 中返回的 sqlMapClient, 而不是 SqlMapClientFactoryBean 自己的实例。

4. 依赖注入(DI)

1) 依赖注入的方式分为构造函数注入和setter方法注入:

 
  1. <bean id="exampleBean" class="examples.ExampleBean">

  2. <constructor-arg index="0" value="7500000"/>

  3. <constructor-arg index="1" ref="bar"/>

  4. </bean>

  5. <bean id="bar" class="x.y.Bar"/>

构造函数注入使用:<constructor-arg index="0" value="7500000"/>, <constructor-arg type="int" value="7500000"/>,对于非简单参数,需要使用ref <constructor-arg index="1" ref="bar"/>

 
  1. <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">

  2. <property name="dataSource" ref="dataSource" />

  3. <property name="configLocation" value="classpath:config/mybatis-config.xml" />

  4. <property name="mapperLocations" value="classpath*:config/mappers/**/*.xml" />

  5. </bean>

setter方法注入使用 <property name="username" value="xxx"/>, 非简单类型属性使用ref <property name="xxbean" ref="xxx"/>

2)集合等复杂类型的注入:

 
  1. <bean id="moreComplexObject" class="example.ComplexObject">

  2. <!-- results in a setAdminEmails(java.util.Properties) call -->

  3. <property name="adminEmails">

  4. <props>

  5. <prop key="administrator">administrator@example.org</prop>

  6. <prop key="support">support@example.org</prop>

  7. <prop key="development">development@example.org</prop>

  8. </props>

  9. </property>

  10. <!-- results in a setSomeList(java.util.List) call -->

  11. <property name="someList">

  12. <list>

  13. <value>a list element followed by a reference</value>

  14. <ref bean="myDataSource" />

  15. </list>

  16. </property>

  17. <!-- results in a setSomeMap(java.util.Map) call -->

  18. <property name="someMap">

  19. <map>

  20. <entry key="an entry" value="just some string"/>

  21. <entry key ="a ref" value-ref="myDataSource"/>

  22. </map>

  23. </property>

  24. <!-- results in a setSomeSet(java.util.Set) call -->

  25. <property name="someSet">

  26. <set>

  27. <value>just some string</value>

  28. <ref bean="myDataSource" />

  29. </set>

  30. </property>

  31. </bean>

也很简单,list属性就是 <list>里面包含<value>或者<ref>或者<bean>, set也类似。map是<map>里面包含<entry>这个也好理解,因为map的实现就是使用内部类Entry来存储key和value. Properties是 <props>里面包含<prop>.

5. <bean> 元素可以配置的属性:

<bean> 除了 id 和 class 属性之外,还有一些可选的属性:

1) scope属性,默认<bean> 的 scope就是 singleton="true", springmvc和struts2的重要区别之一就是spring的controll是单例的,而struts2的action是:scope="prototype" ,还有 scope="request" , scope="session",scope="globalSession"(仅用于portlet)

2)abstract属性,是否是抽象的bean:

 
  1. <bean id="baseDAO" abstract="true">

  2. <property name="dataSource" ref="dataSource" />

  3. <property name="sqlMapClient" ref="sqlMapClient" />

  4. </bean>

  5. <bean id="collectionDAO" class="net.minisns.dal.dao.CollectionDAOImpl"

  6. parent="baseDAO" />

  7. <bean id="commentDAO" class="net.minisns.dal.dao.CommentDAOImpl" parent="baseDAO" />

3)depends-on 依赖于某个bean,其必须先初始化:<bean id="xxx" class="xxx" depends-on="refbean" />

4)lazy-init="true" 是否延迟初始化,默认为 false

5) dependency-check 是否对bean依赖的其它bean进行检查,默认值为 none,可取值有:none, simple, object, all等

6)factory-method 和 factory-bean用于静态工厂和非静态工厂:

 
  1. <bean id="bar" class="...StaticBarInterfaceFactory" factory-method="getInstance"/>

  2. <bean id="barFactory" class="...NonStaticBarInterfaceFactory"/>

  3. <bean id="bar" factory-bean="barFactory" factory-method="getInstance"/>

7)init-method, destory-method 指定bean初始化和死亡时调用的方法,常用于 dataSource的连接池的配置

8) lookup-method 方法注入:

 
  1. <bean id="newsBean" class="..xxx" singleton="false">

  2. <bean id="mockPersister" class="..impl.MockNewsPersister">

  3. <lookup-method name="getNewsBean" bean="newsBean"/>

  4. </bean>

表示 mockPersister 有一个依赖属性 newsBean,该属性的每次注入都是通过调用newsBean.getNewsBean() 方法获得的。

9) autowire 是否启用自动装配依赖,默认为 no, 其它取值还有:byName, byType, constructor

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值