SqlSessionFactoryBean
SqlSessionFactoryBean實(shí)現(xiàn)了FactoryBean接口钧萍,在創(chuàng)建bean時(shí)會(huì)調(diào)用getObject方法尖殃。
@Override
public SqlSessionFactory getObject() throws Exception {
if (this.sqlSessionFactory == null) {
afterPropertiesSet();
}
return this.sqlSessionFactory;
}
如果sqlSessionFactory對(duì)象為空,則調(diào)用 afterPropertiesSet()方法划煮,因?yàn)镾qlSessionFactoryBean還實(shí)現(xiàn)了InitializingBean接口送丰,在bean創(chuàng)建的時(shí)候就會(huì)調(diào)用afterPropertiesSet()方法。所以這步this.sqlSessionFactory == null只是增加個(gè)校驗(yàn)弛秋。
@Override
public void afterPropertiesSet() throws Exception {
notNull(dataSource, "Property 'dataSource' is required");
notNull(sqlSessionFactoryBuilder, "Property 'sqlSessionFactoryBuilder' is required");
state((configuration == null && configLocation == null) || !(configuration != null && configLocation != null),
"Property 'configuration' and 'configLocation' can not specified with together");
this.sqlSessionFactory = buildSqlSessionFactory();
}
afterPropertiesSet方法調(diào)用buildSqlSessionFactory方法創(chuàng)建sqlSessionFactory對(duì)象器躏。buildSqlSessionFactory方法很長(zhǎng),不過主要是給Configuration對(duì)象設(shè)置屬性值蟹略,這里就不貼代碼了登失。
MapperFactoryBean
MapperFactoryBean是用來創(chuàng)建MyBatis Mapper對(duì)象的,MapperFactoryBean也實(shí)現(xiàn)了FactoryBean接口挖炬,間接實(shí)現(xiàn)InitializingBean接口揽浙,我們先看下InitializingBean接口的afterPropertiesSet實(shí)現(xiàn)。
@Override
public final void afterPropertiesSet() throws IllegalArgumentException, BeanInitializationException {
// Let abstract subclasses check their configuration.
checkDaoConfig();
// Let concrete implementations initialize themselves.
try {
//空實(shí)現(xiàn)
initDao();
}
catch (Exception ex) {
throw new BeanInitializationException("Initialization of DAO failed", ex);
}
}
checkDaoConfig方法由MapperFactoryBean實(shí)現(xiàn)意敛。主要是把Mapper接口添加到Configuration對(duì)象中馅巷。
@Override
protected void checkDaoConfig() {
super.checkDaoConfig();
notNull(this.mapperInterface, "Property 'mapperInterface' is required");
//如果Configuration中不存在Mapper,則添加Mapper
Configuration configuration = getSqlSession().getConfiguration();
if (this.addToConfig && !configuration.hasMapper(this.mapperInterface)) {
try {
configuration.addMapper(this.mapperInterface);
} catch (Exception e) {
logger.error("Error while adding the mapper '" + this.mapperInterface + "' to configuration.", e);
throw new IllegalArgumentException(e);
} finally {
ErrorContext.instance().reset();
}
}
}
接下來我們?cè)倏碝apperFactoryBean中的getObject方法草姻。
@Override
public T getObject() throws Exception {
return getSqlSession().getMapper(this.mapperInterface);
}
getObject方法返回Mapper對(duì)象钓猬,Mapper對(duì)象是從Configuration中獲取。