spring mybatis sqlSessionFactory

<!-- 配置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.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean@11e0d39
&sqlSessionFactory—-org.mybatis.spring.SqlSessionFactoryBean@da2e3b
&captchaStoreProxy—-org.springframework.aop.framework.ProxyFactoryBean: 1 interfaces [com.octo.captcha.service.captchastore.CaptchaStore]; 1 advisors [org.springframework.aop.support.NameMatchMethodPointcutAdvisor: advice [com.ylpw.verifycode.ValidateCodeBeforeMethodAdvice@1f64d0c]]; targetSource [SingletonTargetSource for target object [com.octo.captcha.service.captchastore.FastHashMapCaptchaStore@13c5b1e]]; proxyTargetClass=false; optimize=false; opaque=false; exposeProxy=false; frozen=false
&clearStatisticsMethod—-org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean@18224bf
&startQuertz—-org.springframework.scheduling.quartz.SchedulerFactoryBean@13a7b72
&insuranceKbase—-org.drools.container.spring.beans.KnowledgeBaseBeanFactory@7eb371
&insuranceKsession—-org.drools.container.spring.beans.StatelessKnowledgeSessionBeanFactory@36dbaa
&orderKbase—-org.drools.container.spring.beans.KnowledgeBaseBeanFactory@18f92bb
&orderKsession—-org.drools.container.spring.beans.StatelessKnowledgeSessionBeanFactory@ea4019
&defaultCache—-com.google.code.ssm.CacheFactory@1163a30

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值