[上一篇]:Mybatis源碼解析之Spring獲取Mapper過程
菜菜的上一篇《Mybatis源碼解析之Spring獲取Mapper過程》主要介紹的是MapperScan,并從中知道了Spring與MyBatis如何連接起來的嚷辅,這篇菜菜繼續(xù)看配置文件中配置的SqlSessionFactoryBean,并介紹解析MaBatis中配置的xml信息咽筋。
問題
MyBatis中的配置文件是在哪步進(jìn)行解析的瘤载?
揭秘答案-源碼
這里再次貼出上篇中配置文件中部分代碼
@Bean
public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource, ApplicationContext applicationContext) throws Exception {
SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(dataSource);
sessionFactory.setConfigLocation(applicationContext.getResource("classpath:mybatis-config.xml"));
sessionFactory.afterPropertiesSet();
sessionFactory.setPlugins(new Interceptor[] { new PagerInterceptor()});
return sessionFactory;
}
配置文件中配置了SqlSessionFactoryBean的bean,Spring在啟動的時候就會執(zhí)行sqlSessionFactoryBean(DataSource dataSource, ApplicationContext applicationContext)來創(chuàng)建Bean的實(shí)例,該方法中前面都是對屬性進(jìn)行設(shè)置梭依,主要看sessionFactory.afterPropertiesSet();
afterPropertiesSet()是Spring中InitializingBean中的方法,Spring會在初始化Bean時所有的屬性被初始化后調(diào)用該方法稍算。SqlSessionFactoryBean中afterPropertiesSet()方法中最重要的是調(diào)用buildSqlSessionFactory()方法,下面具體看下buildSqlSessionFactory方法
@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();
}
/**
* Build a {@code SqlSessionFactory} instance.
*
* The default implementation uses the standard MyBatis {@code XMLConfigBuilder} API to build a
* {@code SqlSessionFactory} instance based on an Reader.
* Since 1.3.0, it can be specified a {@link Configuration} instance directly(without config file).
*
* @return SqlSessionFactory
* @throws IOException if loading the config file failed
*/
protected SqlSessionFactory buildSqlSessionFactory() throws IOException {
Configuration configuration;
XMLConfigBuilder xmlConfigBuilder = null;
if (this.configuration != null) {
configuration = this.configuration;
if (configuration.getVariables() == null) {
configuration.setVariables(this.configurationProperties);
} else if (this.configurationProperties != null) {
configuration.getVariables().putAll(this.configurationProperties);
}
} else if (this.configLocation != null) {
xmlConfigBuilder = new XMLConfigBuilder(this.configLocation.getInputStream(), null, this.configurationProperties);
configuration = xmlConfigBuilder.getConfiguration();
} else {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Property `configuration` or 'configLocation' not specified, using default MyBatis Configuration");
}
configuration = new Configuration();
configuration.setVariables(this.configurationProperties);
}
if (this.objectFactory != null) {
configuration.setObjectFactory(this.objectFactory);
}
if (this.objectWrapperFactory != null) {
configuration.setObjectWrapperFactory(this.objectWrapperFactory);
}
if (this.vfs != null) {
configuration.setVfsImpl(this.vfs);
}
if (hasLength(this.typeAliasesPackage)) {
String[] typeAliasPackageArray = tokenizeToStringArray(this.typeAliasesPackage,
ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);
for (String packageToScan : typeAliasPackageArray) {
configuration.getTypeAliasRegistry().registerAliases(packageToScan,
typeAliasesSuperType == null ? Object.class : typeAliasesSuperType);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Scanned package: '" + packageToScan + "' for aliases");
}
}
}
if (!isEmpty(this.typeAliases)) {
for (Class<?> typeAlias : this.typeAliases) {
configuration.getTypeAliasRegistry().registerAlias(typeAlias);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Registered type alias: '" + typeAlias + "'");
}
}
}
//如果添加了plugins役拴,最終會將plugins加入interceptorChain
if (!isEmpty(this.plugins)) {
for (Interceptor plugin : this.plugins) {
configuration.addInterceptor(plugin);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Registered plugin: '" + plugin + "'");
}
}
}
if (hasLength(this.typeHandlersPackage)) {
String[] typeHandlersPackageArray = tokenizeToStringArray(this.typeHandlersPackage,
ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);
for (String packageToScan : typeHandlersPackageArray) {
configuration.getTypeHandlerRegistry().register(packageToScan);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Scanned package: '" + packageToScan + "' for type handlers");
}
}
}
if (!isEmpty(this.typeHandlers)) {
for (TypeHandler<?> typeHandler : this.typeHandlers) {
configuration.getTypeHandlerRegistry().register(typeHandler);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Registered type handler: '" + typeHandler + "'");
}
}
}
if (this.databaseIdProvider != null) {//fix #64 set databaseId before parse mapper xmls
try {
configuration.setDatabaseId(this.databaseIdProvider.getDatabaseId(this.dataSource));
} catch (SQLException e) {
throw new NestedIOException("Failed getting a databaseId", e);
}
}
if (this.cache != null) {
configuration.addCache(this.cache);
}
//如果配置了config文件的位置就會去解析改文件一般是mybatis-config.xml文件
if (xmlConfigBuilder != null) {
try {
xmlConfigBuilder.parse();
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Parsed configuration file: '" + this.configLocation + "'");
}
} catch (Exception ex) {
throw new NestedIOException("Failed to parse config resource: " + this.configLocation, ex);
} finally {
ErrorContext.instance().reset();
}
}
if (this.transactionFactory == null) {
this.transactionFactory = new SpringManagedTransactionFactory();
}
configuration.setEnvironment(new Environment(this.environment, this.transactionFactory, this.dataSource));
//如果配置了Mapper文件路徑就會去解析Mapper
if (!isEmpty(this.mapperLocations)) {
for (Resource mapperLocation : this.mapperLocations) {
if (mapperLocation == null) {
continue;
}
try {
XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(mapperLocation.getInputStream(),
configuration, mapperLocation.toString(), configuration.getSqlFragments());
xmlMapperBuilder.parse();
} catch (Exception e) {
throw new NestedIOException("Failed to parse mapping resource: '" + mapperLocation + "'", e);
} finally {
ErrorContext.instance().reset();
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Parsed mapper file: '" + mapperLocation + "'");
}
}
} else {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Property 'mapperLocations' was not specified or no matching resources found");
}
}
return this.sqlSessionFactoryBuilder.build(configuration);
}
//SqlSessionFactoryBuilder
public SqlSessionFactory build(Configuration config) {
return new DefaultSqlSessionFactory(config);
}
在buildSqlSessionFactory中有兩個解析xml文件的地方一個是xmlConfigBuilder解析config文件,另外一個是xmlMapperBuilder用來解析mapper文件河闰。
Spring與MyBatis整合后在上一篇中沒有設(shè)置mapperLocation,所以真正解析Mapper文件的地方并不在這姜性,而是在MapperFactoryBean的checkDaoConfig()里(后面會詳細(xì)說明)
buildSqlSessionFactory最后一步是返回SqlSessionFactory部念,我們看到返回的是DefaultSqlSessionFactory妓湘,Mybatis源碼解析之SqlSession來自何方中知道SqlSessionFactoryBean是個factoryBean,在Spring實(shí)例化bean時會調(diào)用getObject()方法榜贴,而它的getObject()返回的就是buildSqlSessionFactory創(chuàng)建的DefaultSqlSessionFactory竣灌,這樣在Spring中就有了擁有了SqlSessionFactory。
那么秆麸,Mapper文件的解析為什么會是在MapperFactoryBean的checkDaoConfig()里呢
我們首先看下MapperFactoryBean的繼承層次關(guān)系
再來看下DaoSupport這個類
public abstract class DaoSupport implements InitializingBean {
protected final Log logger = LogFactory.getLog(this.getClass());
public DaoSupport() {
}
public final void afterPropertiesSet() throws IllegalArgumentException, BeanInitializationException {
this.checkDaoConfig();
try {
this.initDao();
} catch (Exception var2) {
throw new BeanInitializationException("Initialization of DAO failed", var2);
}
}
protected abstract void checkDaoConfig() throws IllegalArgumentException;
protected void initDao() throws Exception {
}
}
DaoSupport實(shí)現(xiàn)了InitializingBean初嘹,并使用模板方法設(shè)計(jì)模式定義了兩個模板方法checkDaoConfig()與initDao()
由于DaoSupport實(shí)現(xiàn)了InitializingBean所以MapperFactoryBean初始化(為什么進(jìn)行會創(chuàng)建這個bean在下一篇中有講到)屬性完成后就會調(diào)用DaoSupport里的afterPropertiesSet()方法afterPropertiesSet方法首先調(diào)用了this.checkDaoConfig();而MapperFactoryBean實(shí)現(xiàn)了該方法,如下:
/**
* {@inheritDoc}
*/
@Override
protected void checkDaoConfig() {
super.checkDaoConfig();
notNull(this.mapperInterface, "Property 'mapperInterface' is required");
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();
}
}
}
checkDaoConfig()中最重要的方法是configuration.addMapper(this.mapperInterface);為了減少篇幅下面一次性將所有調(diào)用到的源碼知道解析mapper貼出
//Configuration
public <T> void addMapper(Class<T> type) {
mapperRegistry.addMapper(type);
}
//MapperRegistry
public <T> void addMapper(Class<T> type) {
if (type.isInterface()) {
if (hasMapper(type)) {
throw new BindingException("Type " + type + " is already known to the MapperRegistry.");
}
boolean loadCompleted = false;
try {
knownMappers.put(type, new MapperProxyFactory<T>(type));
// It's important that the type is added before the parser is run
// otherwise the binding may automatically be attempted by the
// mapper parser. If the type is already known, it won't try.
MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type);
//這里進(jìn)行解析
parser.parse();
loadCompleted = true;
} finally {
if (!loadCompleted) {
knownMappers.remove(type);
}
}
}
}
//MapperAnnotationBuilder
public void parse() {
String resource = type.toString();
if (!configuration.isResourceLoaded(resource)) {
//先解析xml中的sql
loadXmlResource();
configuration.addLoadedResource(resource);
assistant.setCurrentNamespace(type.getName());
parseCache();
parseCacheRef();
Method[] methods = type.getMethods();
for (Method method : methods) {
try {
// issue #237
if (!method.isBridge()) {
//解析注解中的sql
parseStatement(method);
}
} catch (IncompleteElementException e) {
configuration.addIncompleteMethod(new MethodResolver(this, method));
}
}
}
parsePendingMethods();
}
private void loadXmlResource() {
// Spring may not know the real resource name so we check a flag
// to prevent loading again a resource twice
// this flag is set at XMLMapperBuilder#bindMapperForNamespace
if (!configuration.isResourceLoaded("namespace:" + type.getName())) {
String xmlResource = type.getName().replace('.', '/') + ".xml";
InputStream inputStream = null;
try {
inputStream = Resources.getResourceAsStream(type.getClassLoader(), xmlResource);
} catch (IOException e) {
// ignore, resource is not required
}
if (inputStream != null) {
XMLMapperBuilder xmlParser = new XMLMapperBuilder(inputStream, assistant.getConfiguration(), xmlResource, configuration.getSqlFragments(), type.getName());
xmlParser.parse();
}
}
}
//XMLMapperBuilder
public void parse() {
//這里就是具體解析element了有興趣自己可以看下
if (!configuration.isResourceLoaded(resource)) {
configurationElement(parser.evalNode("/mapper"));
configuration.addLoadedResource(resource);
bindMapperForNamespace();
}
parsePendingResultMaps();
parsePendingChacheRefs();
parsePendingStatements();
}
菜菜相信只要找到了是在configuration.addMapper(this.mapperInterface)里去解析Mapper文件以及Spring怎么進(jìn)入configuration.addMapper(this.mapperInterface)的,后面的具體怎么解析相信大家都能看的明白沮趣,只需要記住一點(diǎn)屯烦,Mybatis的所有配置信息都存放在Configuration里。
如有錯誤房铭,歡迎各位大佬斧正驻龟!
[下一篇]:Mybatis源碼解析之MapperProxy