由于用惯了SpringBoot,最近一朋友在使用SSM时遇到了一些MyBatis配置上的问题,于是我俩拉出信仰中的XML配置文件开始分析起来,主要部分就是下面这个,不难理解sqlSessionFactory中的数据源引用了dataSource
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mapperLocations" value="classpath:mapper/*.xml"/>
</bean>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="jdbcUrl" value="${jdbcUrl}"/>
<property name="driverClass" value="${driverClass}"/>
<property name="user" value="${user}"/>
<property name="password" value="${password}"/>
</bean>
当时便想SpringBoot嘛,自动配置就完事了,肯定是大佬们写了个自动配置类然后放在了META-INF/spring.factories里面,想着便点开了spring-boot-autoconfigure下面的spring.factories,一搜myb,b还没打出来搜索框就红了,找不到,场面一度十分尴尬

后来一想也是,MyBatis版本都要自己写怎么可能事先写好自动配置类呢
1.SpringBoot中MyBatis是怎么配置的
当引用MyBatis场景启动器的时候,点进去看可以找到自动配置依赖!
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-autoconfigure</artifactId>
</dependency>
按照自动配置的思路可以找到自动配置类,配置类里面声明了SqlSessionFactory的Bean,代码大致如下,通过dataSource生成sqlSessionFactory

@Bean
@ConditionalOnMissingBean
public SqlSessionFactory sqlSessionFactory(DataSource dataSource) {...}
其实这个还不是笔者纠结的地方,就在刚才笔者在火星的反射弧终于想明白了下面这个问题
2.SpringBoot中MyBatis配置能自动的原因
在使用MyBatis时一没加配置类声明Bean(其实加了),二没用ComponentScan,自动配置类也不再核心类的包下,笔者百思不得其解,为什么自动配置类声明的Bean能被放入到Spring容器中


网友评论