解决mybatis-spring从1.1升级到1.2所带来问题
该博客主要针对springboot项目
问题背景
最近在使用项目中遇见如下一个错误:
Caused by: java.lang.IllegalArgumentException: Property 'sqlSessionFactory' or 'sqlSessionTemplate' are required
at org.springframework.util.Assert.notNull(Assert.java:134)
at org.mybatis.spring.support.SqlSessionDaoSupport.checkDaoConfig(SqlSessionDaoSupport.java:74)
at org.mybatis.spring.mapper.MapperFactoryBean.checkDaoConfig(MapperFactoryBean.java:73)
at org.springframework.dao.support.DaoSupport.afterPropertiesSet(DaoSupport.java:44)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624)
... 39 more
引发该问题的原因是Mybais-Spring包版本过高(1.2以上)引起的,因为1.2以及以上的版本中,对SqlSessionDaoSupport类中的’sqlSessionFactory’或’sqlSessionTemplate’注入方式进行了调整。
解决办法
在Application启动类中添加注解
@ComponentScan(basePackages = {"pers.jarome.init"})
basePackages 的值为扫描指定的包,init包为指定的springboot初始化配置类
Mybatis初始化类
在springboot启动之前注入该类
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import javax.sql.DataSource;
/**
* @author jarome
* @date 2017/12/22
**/
@Configuration
public class MybatisInitConfig {
@Autowired
private DataSourceProperties dataSourceProperties;
@Bean
public SqlSessionFactory sqlSessionFactoryBean() throws Exception {
DataSource dataSource = dataSourceProperties.initializeDataSourceBuilder().build();
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
//配置扫描地址
//关于application.properties中与mybatis有关的配置,需要在此处配置才会生效
sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:/mapper/*.xml"));
return sqlSessionFactoryBean.getObject();
}
}