<!-- 配置Mybatis -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="configLocation" value="classpath:config/mybatis.xml"></property>
<!-- <property name="mapperLocations" value="/WEB-INF/conf/mappers/*Mapper.xml"></property> -->
<property name="mapperLocations">
<list>
<value>classpath:config/mappers/**Mapper.xml</value>
</list>
</property>
</bean>
<bean id="sqlSessionTemplate" name="sqlSessionTemplate"
class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory"></constructor-arg>
</bean>
在mybatis 配置中經常會發現這樣的配置,但是擷取sqlSessionFactory的時候确實另一個對象 DefaultSqlSessionFactory
為何通過applicationContext.getBean(‘sqlSessionFactory’) 擷取的不是 SqlSessionFactoryBean 了;
問題就是SqlSessionFactoryBean 這個bean實作了FactoryBean接口
public class SqlSessionFactoryBean implements FactoryBean, InitializingBean, ApplicationListener
在調用getBean(‘sqlSessionFactory’)的時候傳回的是 SqlSessionFactoryBean 實作的getObject() 對象;
public SqlSessionFactory getObject() throws Exception {
if (this.sqlSessionFactory == null) {
afterPropertiesSet();
}
return this.sqlSessionFactory;
}
傳回的就是一個sqlSessionFactory 這個 sqlSessionFactory 就是通過的buildSqlSessionFactory() 建構的
protected SqlSessionFactory buildSqlSessionFactory() throws IOException {
Configuration configuration;
XMLConfigBuilder xmlConfigBuilder = null;
if (this.configLocation != null) {
xmlConfigBuilder = new XMLConfigBuilder(this.configLocation.getInputStream(), null, this.configurationProperties);
configuration = xmlConfigBuilder.getConfiguration();
} else {
if (logger.isDebugEnabled()) {
logger.debug("Property '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 (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 + "'");
}
}
}
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 (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();
}
Environment environment = new Environment(this.environment, this.transactionFactory, this.dataSource);
configuration.setEnvironment(environment);
if (this.databaseIdProvider != null) {
try {
configuration.setDatabaseId(this.databaseIdProvider.getDatabaseId(this.dataSource));
} catch (SQLException e) {
throw new NestedIOException("Failed getting a databaseId", e);
}
}
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);
}
最主要的問題是為何擷取bean的時候調用的是getObejct()
protected Object getObjectForBeanInstance(
Object beanInstance, String name, String beanName, RootBeanDefinition mbd) {
// Don't let calling code try to dereference the factory if the bean isn't a factory.
if (BeanFactoryUtils.isFactoryDereference(name) && !(beanInstance instanceof FactoryBean)) {
throw new BeanIsNotAFactoryException(transformedBeanName(name), beanInstance.getClass());
}
// Now we have the bean instance, which may be a normal bean or a FactoryBean.
// If it's a FactoryBean, we use it to create a bean instance, unless the
// caller actually wants a reference to the factory.
if (!(beanInstance instanceof FactoryBean) || BeanFactoryUtils.isFactoryDereference(name)) {
return beanInstance;
}
Object object = null;
if (mbd == null) {
object = getCachedObjectForFactoryBean(beanName);
}
if (object == null) {
// Return bean instance from factory.
FactoryBean<?> factory = (FactoryBean<?>) beanInstance;
// Caches object obtained from FactoryBean if it is a singleton.
if (mbd == null && containsBeanDefinition(beanName)) {
mbd = getMergedLocalBeanDefinition(beanName);
}
boolean synthetic = (mbd != null && mbd.isSynthetic());
object = getObjectFromFactoryBean(factory, beanName, !synthetic);
}
return object;
}
如果對象沒有實作 FactoryBean 就直接傳回了,實作了還需要做處理
if (!(beanInstance instanceof FactoryBean) || BeanFactoryUtils.isFactoryDereference(name)) {
return beanInstance;
}
具體debug可以參考AbstractBeanFactory.getObjectForBeanInstance()
那麼我們如何擷取真正的SqlSessionFactoryBean了
第一種方式
context.getBean(“&sqlSessionFactory”);
注 前面添加了&的都是事先了FactoryBean類的
第二種方式
context.getBean(SqlSessionFactoryBean.class)
如果要擷取所有的FactoryBean
context.getBean(FactoryBean.class);
//擷取所有實作了 FactoryBean.class 的接口 可以看出列印的名稱都是添加了&類似的
String[] fbeans =context.getBeanNamesForType(FactoryBean.class);
for (int i = 0; i < fbeans.length; i++) {
System.out.println(fbeans[i]+”—-“+context.getBean(fbeans[i]));
}
//輸出結果如下:
&sessionFactory—-org.springf[email protected]11e0d39
&sqlSessionFactory—[email protected]
&captchaStoreProxy—-org.springframework.aop.framework.ProxyFactoryBean: 1 interfaces [com.octo.captcha.service.captchastore.CaptchaStore]; 1 advisors [org.springframework.aop.support.NameMatchMethodPointcutAdvisor: advice [[email protected]]]; targetSource [SingletonTargetSource for target object [[email protected]c5b1e]]; proxyTargetClass=false; optimize=false; opaque=false; exposeProxy=false; frozen=false
&clearStatisticsMethod—-org.sprin[email protected]18224bf
&startQuertz—[email protected]b72
&insuranceKbase—[email protected]71
&insuranceKsession—-org.dro[email protected]36dbaa
&orderKbase—[email protected]2bb
&orderKsession—-org.dro[email protected]ea4019
&defaultCache—[email protected]