https://www.cnblogs.com/digdeep/p/4518571.html
說(shuō)到Spring框架,人們往往大談特談一些似乎高逼格的東西,比如依賴(lài)注入,控制反轉(zhuǎn),面向切面等等。但是卻忘記了最基本的一點(diǎn),Spring的本質(zhì)是一個(gè)bean工廠(beanFactory)或者說(shuō)bean容器,它按照我們的要求,生產(chǎn)我們需要的各種各樣的bean,提供給我們使用。只是在生產(chǎn)bean的過(guò)程中,需要解決bean之間的依賴(lài)問(wèn)題,才引入了依賴(lài)注入(DI)這種技術(shù)。也就是說(shuō)依賴(lài)注入是beanFactory生產(chǎn)bean時(shí)為了解決bean之間的依賴(lài)的一種技術(shù)而已。
那么我們?yōu)槭裁葱枰猄pring框架來(lái)給我們提供這個(gè)beanFactory的功能呢?原因是一般我們認(rèn)為是,可以將原來(lái)硬編碼的依賴(lài),通過(guò)Spring這個(gè)beanFactory這個(gè)工長(zhǎng)來(lái)注入依賴(lài),也就是說(shuō)原來(lái)只有依賴(lài)方和被依賴(lài)方,現(xiàn)在我們引入了第三方——spring這個(gè)beanFactory,由它來(lái)解決bean之間的依賴(lài)問(wèn)題,達(dá)到了松耦合的效果;這個(gè)只是原因之一,還有一個(gè)更加重要的原因:在沒(méi)有spring這個(gè)beanFactory之前,我們都是直接通過(guò)new來(lái)實(shí)例化各種對(duì)象,現(xiàn)在各種對(duì)象bean的生產(chǎn)都是通過(guò)beanFactory來(lái)實(shí)例化的,這樣的話,spring這個(gè)beanFactory就可以在實(shí)例化bean的過(guò)程中,做一些小動(dòng)作——在實(shí)例化bean的各個(gè)階段進(jìn)行一些額外的處理,也就是說(shuō)beanFactory會(huì)在bean的生命周期的各個(gè)階段中對(duì)bean進(jìn)行各種管理,并且spring將這些階段通過(guò)各種接口暴露給我們,讓我們可以對(duì)bean進(jìn)行各種處理,我們只要讓bean實(shí)現(xiàn)對(duì)應(yīng)的接口,那么spring就會(huì)在bean的生命周期調(diào)用我們實(shí)現(xiàn)的接口來(lái)處理該bean。
1. bean容器的啟動(dòng)
bean在實(shí)例化之前,必須是在bean容器啟動(dòng)之后。所以就有了兩個(gè)階段:
1)bean容器的啟動(dòng)階段;
2)容器中bean的實(shí)例化階段;
在啟動(dòng)階段,
1> 首先是讀取bean的xml配置文件,然后解析xml文件中的各種bean的定義,將xml文件中的每一個(gè)<bean />元素分別轉(zhuǎn)換成一個(gè)BeanDefinition對(duì)象,其中保存了從配置文件中讀取到的該bean的各種信息:
public abstract class AbstractBeanDefinition extends BeanMetadataAttributeAccessor
implements BeanDefinition, Cloneable {
private volatile Object beanClass;
private String scope = SCOPE_DEFAULT;
private boolean abstractFlag = false;
private boolean lazyInit = false;
private int autowireMode = AUTOWIRE_NO;
private int dependencyCheck = DEPENDENCY_CHECK_NONE;
private String[] dependsOn;private ConstructorArgumentValues constructorArgumentValues;
private MutablePropertyValues propertyValues;private String factoryBeanName;
private String factoryMethodName;
private String initMethodName;
private String destroyMethodName;
beanClass保存bean的class屬性,scop保存bean是否單例,abstractFlag保存該bean是否抽象,lazyInit保存是否延遲初始化,autowireMode保存是否自動(dòng)裝配,dependencyCheck保存是否堅(jiān)持依賴(lài),dependsOn保存該bean依賴(lài)于哪些bean(這些bean必須提取初始化),constructorArgumentValues保存通過(guò)構(gòu)造函數(shù)注入的依賴(lài),propertyValues保存通過(guò)setter方法注入的依賴(lài),factoryBeanName和factoryMethodName用于factorybean,也就是工廠類(lèi)型的bean,initMethodName和destroyMethodName分別對(duì)應(yīng)bean的init-method和destory-method屬性,比如:
<bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
讀完配置文件之后,得到了很多的BeanDefinition對(duì)象,
2> 然后通過(guò)BeanDefinitionRegistry將這些bean注冊(cè)到beanFactory中:
public interface BeanDefinitionRegistry extends AliasRegistry {
void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)throws BeanDefinitionStoreException;
void removeBeanDefinition(String beanName) throws NoSuchBeanDefinitionException;
BeanDefinition getBeanDefinition(String beanName) throws NoSuchBeanDefinitionException;
boolean containsBeanDefinition(String beanName);
String[] getBeanDefinitionNames();
int getBeanDefinitionCount();
boolean isBeanNameInUse(String beanName);
}
BeanFactory的實(shí)現(xiàn)類(lèi),需要實(shí)現(xiàn)BeanDefinitionRegistry 接口:
@SuppressWarnings("serial")
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
/** Map of bean definition objects, keyed by bean name */
private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<String, BeanDefinition>(64);
@Override
public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
throws BeanDefinitionStoreException {
// ... ...
this.beanDefinitionMap.put(beanName, beanDefinition);
// ... ...
}
我們看到BeanDefinition被注冊(cè)到了 DefaultListableBeanFactory, 保存在它的一個(gè)ConcurrentHashMap中。
將BeanDefinition注冊(cè)到了beanFactory之后,在這里Spring為我們提供了一個(gè)擴(kuò)展的切口,允許我們通過(guò)實(shí)現(xiàn)接口BeanFactoryPostProcessor 在此處來(lái)插入我們定義的代碼:
public interface BeanFactoryPostProcessor {
/**
* Modify the application context's internal bean factory after its standard
* initialization. All bean definitions will have been loaded, but no beans
* will have been instantiated yet. This allows for overriding or adding
* properties even to eager-initializing beans.
* @param beanFactory the bean factory used by the application context
* @throws org.springframework.beans.BeansException in case of errors
*/
void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException;
}
典型的例子就是:PropertyPlaceholderConfigurer,我們一般在配置數(shù)據(jù)庫(kù)的dataSource時(shí)使用到的占位符的值,就是它注入進(jìn)去的:
public abstract class PropertyResourceConfigurer extends PropertiesLoaderSupport
implements BeanFactoryPostProcessor, PriorityOrdered {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
try {
Properties mergedProps = mergeProperties();
// Convert the merged properties, if necessary.
convertProperties(mergedProps);
// Let the subclass process the properties.
processProperties(beanFactory, mergedProps);
}
catch (IOException ex) {
throw new BeanInitializationException("Could not load properties", ex);
}
}
processProperties(beanFactory, mergedProps);在子類(lèi)中實(shí)現(xiàn)的,功能就是將
<bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<property name="url" value="${jdbc_url}" />
<property name="username" value="${jdbc_username}" />
<property name="password" value="${jdbc_password}" />
${jdbc_username}等等這些替換成實(shí)際值。
bean的實(shí)例化階段
實(shí)例化階段主要是通過(guò)反射或者CGLIB對(duì)bean進(jìn)行實(shí)例化,在這個(gè)階段Spring又給我們暴露了很多的擴(kuò)展點(diǎn):
1> 各種的Aware接口,比如 BeanFactoryAware,MessageSourceAware,ApplicationContextAware
對(duì)于實(shí)現(xiàn)了這些Aware接口的bean,在實(shí)例化bean時(shí)Spring會(huì)幫我們注入對(duì)應(yīng)的:BeanFactory, MessageSource,ApplicationContext的實(shí)例:
public interface BeanFactoryAware extends Aware {
/**
* Callback that supplies the owning factory to a bean instance.
* <p>Invoked after the population of normal bean properties
* but before an initialization callback such as
* {@link InitializingBean#afterPropertiesSet()} or a custom init-method.
* @param beanFactory owning BeanFactory (never {@code null}).
* The bean can immediately call methods on the factory.
* @throws BeansException in case of initialization errors
* @see BeanInitializationException
*/
void setBeanFactory(BeanFactory beanFactory) throws BeansException;
}
public interface ApplicationContextAware extends Aware {
/**
* Set the ApplicationContext that this object runs in.
* Normally this call will be used to initialize the object.
* <p>Invoked after population of normal bean properties but before an init callback such
* as {@link org.springframework.beans.factory.InitializingBean#afterPropertiesSet()}
* or a custom init-method. Invoked after {@link ResourceLoaderAware#setResourceLoader},
* {@link ApplicationEventPublisherAware#setApplicationEventPublisher} and
* {@link MessageSourceAware}, if applicable.
* @param applicationContext the ApplicationContext object to be used by this object
* @throws ApplicationContextException in case of context initialization errors
* @throws BeansException if thrown by application context methods
* @see org.springframework.beans.factory.BeanInitializationException
*/
void setApplicationContext(ApplicationContext applicationContext) throws BeansException;
}
public interface MessageSourceAware extends Aware {
/**
* Set the MessageSource that this object runs in.
* <p>Invoked after population of normal bean properties but before an init
* callback like InitializingBean's afterPropertiesSet or a custom init-method.
* Invoked before ApplicationContextAware's setApplicationContext.
* @param messageSource message sourceto be used by this object
*/
void setMessageSource(MessageSource messageSource);
}
2> BeanPostProcessor接口
實(shí)現(xiàn)了BeanPostProcessor接口的bean,在實(shí)例化bean時(shí)Spring會(huì)幫我們調(diào)用接口中的方法:
public interface BeanPostProcessor {
/**
* Apply this BeanPostProcessor to the given new bean instance <i>before</i> any bean
* initialization callbacks (like InitializingBean's {@code afterPropertiesSet}
* or a custom init-method). The bean will already be populated with property values.
* The returned bean instance may be a wrapper around the original.*/
Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException;
/**
* Apply this BeanPostProcessor to the given new bean instance <i>after</i> any bean
* initialization callbacks (like InitializingBean's {@code afterPropertiesSet}
* or a custom init-method). The bean will already be populated with property values.
* The returned bean instance may be a wrapper around the original.*/
Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException;
}
從注釋中可以知道 postProcessBeforeInitialization方法在 InitializingBean接口的 afterPropertiesSet方法之前執(zhí)行,而postProcessAfterInitialization方法在 InitializingBean接口的afterPropertiesSet方法之后執(zhí)行。
3> InitializingBean接口
實(shí)現(xiàn)了InitializingBean接口的bean,在實(shí)例化bean時(shí)Spring會(huì)幫我們調(diào)用接口中的方法:
public interface InitializingBean {
/**
* Invoked by a BeanFactory after it has set all bean properties supplied
* (and satisfied BeanFactoryAware and ApplicationContextAware).
* <p>This method allows the bean instance to perform initialization only
* possible when all bean properties have been set and to throw an
* exception in the event of misconfiguration.
* @throws Exception in the event of misconfiguration (such
* as failure to set an essential property) or if initialization fails.
*/
void afterPropertiesSet() throws Exception;
}
4> DisposableBean接口
實(shí)現(xiàn)了BeanPostProcessor接口的bean,在該bean死亡時(shí)Spring會(huì)幫我們調(diào)用接口中的方法:
public interface DisposableBean {
/**
* Invoked by a BeanFactory on destruction of a singleton.
* @throws Exception in case of shutdown errors.
* Exceptions will get logged but not rethrown to allow
* other beans to release their resources too.
*/
void destroy() throws Exception;
}
InitializingBean接口 和 DisposableBean接口對(duì)應(yīng)于 <bean /> 的 init-method 和 destory-method 屬性,其經(jīng)典的例子就是dataSource:
<bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
所以在Spring初始化 dataSource 這個(gè)bean之后會(huì)調(diào)用 DruidDataSource.init 方法:
public void init() throws SQLException {
// ... ...try {
lock.lockInterruptibly();
} catch (InterruptedException e) {
throw new SQLException("interrupt", e);
}
boolean init = false;
try {
connections = new DruidConnectionHolder[maxActive];
SQLException connectError = null;
try {
for (int i = 0, size = getInitialSize(); i < size; ++i) {
Connection conn = createPhysicalConnection();
DruidConnectionHolder holder = new DruidConnectionHolder(this, conn);
connections[poolingCount++] = holder;
}
if (poolingCount > 0) {
poolingPeak = poolingCount;
poolingPeakTime = System.currentTimeMillis();
}
} catch (SQLException ex) {
LOG.error("init datasource error", ex);
connectError = ex;
}
} catch (SQLException e) {
LOG.error("dataSource init error", e);
throw e;
} catch (InterruptedException e) {
throw new SQLException(e.getMessage(), e);
} finally {
inited = true;
lock.unlock();
}
}
基本就是初始化數(shù)據(jù)庫(kù)連接池。
在dataSource 這個(gè)bean死亡時(shí)會(huì)調(diào)用 DruidDataSource.close()方法:
public void close() {
lock.lock();
try {
for (int i = 0; i < poolingCount; ++i) {
try {
DruidConnectionHolder connHolder = connections[i];
for (PreparedStatementHolder stmtHolder : connHolder.getStatementPool().getMap().values()) {
connHolder.getStatementPool().closeRemovedStatement(stmtHolder);
}
connHolder.getStatementPool().getMap().clear();
Connection physicalConnection = connHolder.getConnection();
physicalConnection.close();
connections[i] = null;
destroyCount.incrementAndGet();
} catch (Exception ex) {
LOG.warn("close connection error", ex);
}
}
} finally {
lock.unlock();
}
}
基本就是關(guān)閉連接池中的連接。
另外注解 @PostConstruct 和 @PreDestroy 也能達(dá)到 InitializingBean接口 和 DisposableBean接口的效果。
2. 總結(jié)
spring容器接管了bean的實(shí)例化,不僅僅是通過(guò)依賴(lài)注入達(dá)到了松耦合的效果,同時(shí)給我們提供了各種的擴(kuò)展接口,來(lái)在bean的生命周期的各個(gè)時(shí)期插入我們自己的代碼:
0)BeanFactoryPostProcessor接口(在容器啟動(dòng)階段)
1)各種的Aware接口
2)BeanPostProcessor接口
3)InitializingBean接口(@PostConstruct, init-method)
4)DisposableBean接口(@PreDestroy, destory-method)
3. FactoryBean接口
實(shí)現(xiàn)了FactoryBean接口的bean是一類(lèi)叫做factory的bean。其特點(diǎn)是,spring會(huì)在使用getBean()調(diào)用獲得該bean時(shí),會(huì)自動(dòng)調(diào)用該bean的getObject()方法,所以返回的不是factory這個(gè)bean,而是這個(gè)bean.getOjbect()方法的返回值:
public interface FactoryBean<T> {
T getObject() throws Exception;
Class<?> getObjectType();
boolean isSingleton();
}
典型的例子有spring與mybatis的結(jié)合:
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:config/mybatis-config-master.xml" />
<property name="mapperLocations" value="classpath*:config/mappers/master/**/*.xml" />
</bean>
我們看上面該bean,因?yàn)閷?shí)現(xiàn)了FactoryBean接口,所以返回的不是 SqlSessionFactoryBean 的實(shí)例,而是她的 SqlSessionFactoryBean.getObject() 的返回值:
public class SqlSessionFactoryBean implements FactoryBean<SqlSessionFactory>, InitializingBean, ApplicationListener<ApplicationEvent> {
private static final Log logger = LogFactory.getLog(SqlSessionFactoryBean.class);
private Resource configLocation;
private Resource[] mapperLocations;
private DataSource dataSource;
public SqlSessionFactory getObject() throws Exception {
if (this.sqlSessionFactory == null) {
afterPropertiesSet();
}
return this.sqlSessionFactory;
}
其實(shí)他是一個(gè)專(zhuān)門(mén)生產(chǎn) sqlSessionFactory 的工廠,所以才叫 SqlSessionFactoryBean。 而SqlSessionFactory又是生產(chǎn)SqlSession的工廠。
還有spring與ibatis的結(jié)合:
<!-- Spring提供的iBatis的SqlMap配置 -->
<bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
<property name="configLocation" value="classpath:sqlmap/sqlmap-config.xml" />
<property name="dataSource" ref="dataSource" />
</bean>
public class SqlMapClientFactoryBean implements FactoryBean<SqlMapClient>, InitializingBean {
private Resource[] configLocations;
private Resource[] mappingLocations;
private Properties sqlMapClientProperties;
private DataSource dataSource;
private boolean useTransactionAwareDataSource = true;
private Class transactionConfigClass = ExternalTransactionConfig.class;
private Properties transactionConfigProperties;
private LobHandler lobHandler;
private SqlMapClient sqlMapClient;
public SqlMapClient getObject() {
return this.sqlMapClient;
}
SqlMapClientFactoryBean 返回的是 getObject() 中返回的 sqlMapClient, 而不是 SqlMapClientFactoryBean 自己的實(shí)例。</pre>
4. 依賴(lài)注入(DI)
1) 依賴(lài)注入的方式分為構(gòu)造函數(shù)注入和setter方法注入:
<bean id="exampleBean" class="examples.ExampleBean">
<constructor-arg index="0" value="7500000"/>
<constructor-arg index="1" ref="bar"/>
</bean>
<bean id="bar" class="x.y.Bar"/>
構(gòu)造函數(shù)注入使用:<constructor-arg index="0" value="7500000"/>, <constructor-arg type="int" value="7500000"/>,對(duì)于非簡(jiǎn)單參數(shù),需要使用ref <constructor-arg index="1" ref="bar"/>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:config/mybatis-config.xml" />
<property name="mapperLocations" value="classpath*:config/mappers/**/*.xml" />
</bean>
setter方法注入使用 <property name="username" value="xxx"/>, 非簡(jiǎn)單類(lèi)型屬性使用ref <property name="xxbean" ref="xxx"/>
2)集合等復(fù)雜類(lèi)型的注入:
<bean id="moreComplexObject" class="example.ComplexObject">
<!-- results in a setAdminEmails(java.util.Properties) call -->
<property name="adminEmails">
<props>
<prop key="administrator">administrator@example.org</prop>
<prop key="support">support@example.org</prop>
<prop key="development">development@example.org</prop>
</props>
</property>
<!-- results in a setSomeList(java.util.List) call -->
<property name="someList">
<list>
<value>a list element followed by a reference</value>
<ref bean="myDataSource" />
</list>
</property>
<!-- results in a setSomeMap(java.util.Map) call -->
<property name="someMap">
<map>
<entry key="an entry" value="just some string"/>
<entry key ="a ref" value-ref="myDataSource"/>
</map>
</property>
<!-- results in a setSomeSet(java.util.Set) call -->
<property name="someSet">
<set>
<value>just some string</value>
<ref bean="myDataSource" />
</set>
</property>
</bean>
也很簡(jiǎn)單,list屬性就是 <list>里面包含<value>或者<ref>或者<bean>, set也類(lèi)似。map是<map>里面包含<entry>這個(gè)也好理解,因?yàn)閙ap的實(shí)現(xiàn)就是使用內(nèi)部類(lèi)Entry來(lái)存儲(chǔ)key和value. Properties是 <props>里面包含<prop>.
5. <bean> 元素可以配置的屬性:
<bean> 除了 id 和 class 屬性之外,還有一些可選的屬性:
1) scope屬性,默認(rèn)<bean> 的 scope就是 singleton="true", springmvc和struts2的重要區(qū)別之一就是spring的controll是單例的,而struts2的action是:scope="prototype" ,還有 scope="request" , scope="session",scope="globalSession"(僅用于portlet)
2)abstract屬性,是否是抽象的bean:
<bean id="baseDAO" abstract="true">
<property name="dataSource" ref="dataSource" />
<property name="sqlMapClient" ref="sqlMapClient" />
</bean>
<bean id="collectionDAO" class="net.minisns.dal.dao.CollectionDAOImpl" parent="baseDAO" />
<bean id="commentDAO" class="net.minisns.dal.dao.CommentDAOImpl" parent="baseDAO" />
3)depends-on 依賴(lài)于某個(gè)bean,其必須先初始化:<bean id="xxx" class="xxx" depends-on="refbean" />
4)lazy-init="true" 是否延遲初始化,默認(rèn)為 false
5) dependency-check 是否對(duì)bean依賴(lài)的其它bean進(jìn)行檢查,默認(rèn)值為 none,可取值有:none, simple, object, all等
6)factory-method 和 factory-bean用于靜態(tài)工廠和非靜態(tài)工廠:
<bean id="bar" class="...StaticBarInterfaceFactory" factory-method="getInstance"/>
<bean id="barFactory" class="...NonStaticBarInterfaceFactory"/>
<bean id="bar" factory-bean="barFactory" factory-method="getInstance"/>
7)init-method, destory-method 指定bean初始化和死亡時(shí)調(diào)用的方法,常用于 dataSource的連接池的配置
**8) **lookup-method 方法注入:
<bean id="newsBean" class="..xxx" singleton="false">
<bean id="mockPersister" class="..impl.MockNewsPersister">
<lookup-method name="getNewsBean" bean="newsBean"/>
</bean>
表示 mockPersister 有一個(gè)依賴(lài)屬性 newsBean,該屬性的每次注入都是通過(guò)調(diào)用newsBean.getNewsBean() 方法獲得的。
9) autowire 是否啟用自動(dòng)裝配依賴(lài),默認(rèn)為 no, 其它取值還有:byName, byType, constructor