由于用慣了SpringBoot,最近一朋友在使用SSM時(shí)遇到了一些MyBatis配置上的問題奕筐,于是我倆拉出信仰中的XML配置文件開始分析起來脑沿,主要部分就是下面這個(gè)屎即,不難理解sqlSessionFactory中的數(shù)據(jù)源引用了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>
當(dāng)時(shí)便想SpringBoot嘛衔蹲,自動(dòng)配置就完事了庄拇,肯定是大佬們寫了個(gè)自動(dòng)配置類然后放在了META-INF/spring.factories里面,想著便點(diǎn)開了spring-boot-autoconfigure下面的spring.factories耸三,一搜myb,b還沒打出來搜索框就紅了浇揩,找不到仪壮,場(chǎng)面一度十分尷尬后來一想也是,MyBatis版本都要自己寫怎么可能事先寫好自動(dòng)配置類呢
1.SpringBoot中MyBatis是怎么配置的
當(dāng)引用MyBatis場(chǎng)景啟動(dòng)器的時(shí)候胳徽,點(diǎn)進(jìn)去看可以找到自動(dòng)配置依賴!
<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>
按照自動(dòng)配置的思路可以找到自動(dòng)配置類积锅,配置類里面聲明了SqlSessionFactory的Bean,代碼大致如下养盗,通過dataSource生成sqlSessionFactory @Bean
@ConditionalOnMissingBean
public SqlSessionFactory sqlSessionFactory(DataSource dataSource) {...}
其實(shí)這個(gè)還不是筆者糾結(jié)的地方缚陷,就在剛才筆者在火星的反射弧終于想明白了下面這個(gè)問題
2.SpringBoot中MyBatis配置能自動(dòng)的原因
在使用MyBatis時(shí)一沒加配置類聲明Bean(其實(shí)加了),二沒用ComponentScan往核,自動(dòng)配置類也不再核心類的包下蹬跃,筆者百思不得其解,為什么自動(dòng)配置類聲明的Bean能被放入到Spring容器中