SqlSessionFactoryBean的构建流程
目的
此文的主旨在于梳理SqlSessionFactoryBean的初始流程,不拘泥于實(shí)現(xiàn)細(xì)節(jié)。
使用
SqlSessionFactoryBean的主要作用便是用來創(chuàng)建SqlSessionFactory,在它的構(gòu)建過程中會(huì)解析MyBatis所需要的配置文件,將所有配置都封裝到Configuration類中,最后返回SqlSessionFactory實(shí)例。SqlSessionFactoryBean實(shí)現(xiàn)了Spring中兩個(gè)用于初始化Bean的接口FactoryBean、InitializingBean.
InitializingBean定義如下
public interface InitializingBean {/*** 此方法在BeanFactory設(shè)置了Bean配置里的所有屬性后執(zhí)行。*/void afterPropertiesSet() throws Exception;
} 我們一般在XML中都會(huì)有這么一段配置,如下:
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><!-- 注入連接池 --><property name="dataSource" ref="dataSource"/><!--主配置 --><property name="configuration"><bean class="org.apache.ibatis.session.Configuration"><property name="mapUnderscoreToCamelCase" value="true"/></bean></property><!-- 加載mybatis映射文件 --><property name="mapperLocations" value="classpath:mappers/*.xml"/>
</bean> 上述配置的作用就是讓容器創(chuàng)建一個(gè)ID為sqlSessionFactory的SqlSessionFactoryBean實(shí)例,并且為實(shí)例指定了datasource屬性,手動(dòng)指定了主配置對(duì)象,開啟MyBatis下劃線轉(zhuǎn)駝峰的屬性配置,并且指定映射文件所在的位置。
注:
雖然指定的是SqlSessionFactoryBean實(shí)例,但是因?yàn)槔^承了FactoryBean接口,因此我們從容器拿到的對(duì)象實(shí)際上是getObject方法返回的對(duì)象,即SqlSessionFactory實(shí)例。
創(chuàng)建流程
首先自不用說,Spring會(huì)創(chuàng)建SqlSessionFactoryBean實(shí)例,設(shè)置配置的所有屬性,這是第一步,接下來便會(huì)走afterPropertiesSet()方法。
@Override
public void afterPropertiesSet() throws Exception {// 檢查數(shù)據(jù)源notNull(dataSource, "Property 'dataSource' is required");// 檢查SqlSessionFactoryBuilder, 已經(jīng)在構(gòu)造方法里初始化notNull(sqlSessionFactoryBuilder, "Property 'sqlSessionFactoryBuilder' is required");// configuration實(shí)例與configLocation只能有一個(gè)state((configuration == null && configLocation == null) || !(configuration != null && configLocation != null),"Property 'configuration' and 'configLocation' can not specified with together");// 解析配置文件,創(chuàng)建SqlSessionFactory。這屬于MyBatis本身的內(nèi)容,不再展開說明。this.sqlSessionFactory = buildSqlSessionFactory();
} 創(chuàng)建SqlSessionFactory的過程與MyBatis不同的點(diǎn)主要在與transactionFactory,在創(chuàng)建事務(wù)工廠時(shí)不再使用MyBatis自帶的JdbcTransaction類,而是使用SpringManagedTransactionFactory這個(gè)新的事務(wù)工廠類,這個(gè)事務(wù)獲取到的連接全部來自于Spring管理,這樣把事務(wù)全權(quán)交給Spring管理,而MyBatis本身不再涉及事務(wù)管理。如果在使用Spring時(shí)沒有配置(使用)事務(wù),那么獲取到的連接取決于DataSource,無論拿到的連接是自動(dòng)提交還是手動(dòng)提交,MyBatis每一次方法調(diào)用都會(huì)視情況提交或回滾。當(dāng)然對(duì)于自動(dòng)提交而言,MyBatis的commit或者rollbakc是不會(huì)調(diào)用conn.commit()或conn.rollback。
在經(jīng)過afterPropertiesSet方法后,SqlSessionFactory實(shí)例便創(chuàng)建完畢。需要使用SqlSessionFactory實(shí)例便會(huì)調(diào)用getObject方法。
@Override
public SqlSessionFactory getObject() throws Exception {if (this.sqlSessionFactory == null) {afterPropertiesSet();}return this.sqlSessionFactory;
}
轉(zhuǎn)載于:https://www.cnblogs.com/wt20/p/10470872.html
總結(jié)
以上是生活随笔為你收集整理的SqlSessionFactoryBean的构建流程的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 求一个姓欧阳好听的男孩名字。
- 下一篇: Linux-CentOS 查看(监控)服