springboot+mybatis+druid集成,同时解决warn警告
增加DataSource配置文件
#用户中心数据源
spring.datasource.url=jdbc:mysql://localhost:3306/mysql?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# 下面为连接池的补充设置,应用到上面所有数据源中
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20
# 配置获取连接等待超时的时间
spring.datasource.maxWait=6000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
spring.datasource.timeBetweenEvictionRunsMillis=6000
# 配置一个连接在池中最小生存的时间,单位是毫秒
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=SELECT 1
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
spring.datasource.filters=stat,wall
spring.datasource.logSlowSql=true
#druid监控台配置信息
spring.druid.allow=127.0.0.1
spring.druid.loginUsername=root
spring.druid.loginPassword=root
spring.druid.logSlowSql=true
配置dataSource的Bean
@Configuration
@PropertySource("classpath:dataSource.properties")
public class DataSourceConfiguration {
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource dataSource() {
return new DruidDataSource();
}
@Bean
@ConfigurationProperties(prefix="spring.druid")
public HashMap druidProperties() {
return new HashMap();
}
/**
* Title: druidServlet
* Description: druid监控servlet
*
* @param
* @return org.springframework.boot.web.servlet.ServletRegistrationBean
* @date 2019-01-21 14:44
*/
@Bean
public ServletRegistrationBean druidServlet(@Qualifier("druidProperties") HashMap druidProperties) {
ServletRegistrationBean reg = new ServletRegistrationBean();
reg.setServlet(new StatViewServlet());
reg.addUrlMappings("/druid/*");
reg.setInitParameters(druidProperties);
return reg;
}
/**
* Title: filterRegistrationBean
* Description: druid监控请求拦截
*
* @param
* @return org.springframework.boot.web.servlet.FilterRegistrationBean
* @date 2019-01-21 14:46
*/
@Bean
public FilterRegistrationBean filterRegistrationBean() {
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
filterRegistrationBean.setFilter(new WebStatFilter());
filterRegistrationBean.addUrlPatterns("/*");
filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
filterRegistrationBean.addInitParameter("profileEnable", "true");
return filterRegistrationBean;
}
}
第一步已完成,springboot集成Druid完成。
@Configuration
public class MybatisConfiguration {
@Bean
public SqlSessionFactory sqlSessionFactory(@Autowired DataSource dataSource) {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
try {
// 加载MyBatis配置文件
PathMatchingResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
// 能加载多个,所以可以配置通配符(如:classpath*:mapper/**/*.xml)
sqlSessionFactoryBean.setMapperLocations(
resourcePatternResolver.getResources("classpath:com/seeyon/capp/orderservice/**/*.xml"));
return sqlSessionFactoryBean.getObject();
} catch (Exception e) {
log.error("SqlSessionFactory create error!", e);
}
return null;
}
@Bean
public DataSourceTransactionManager dataSourceTransactionManager(@Autowired DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
}
第二步基本完成,一般还需要配置mapper自动扫描。
这里有两种方式
@Bean
public MapperScannerConfigurer mapperScannerConfigurer() {
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
mapperScannerConfigurer.setBasePackage("com.seeyon.capp.orderservice.**.*mapper");
mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
return mapperScannerConfigurer;
}
或者
@SpringBootApplication()
@MapperScan(basePackages = "com.seeyon.capp.orderservice.**.*mapper")
public class MainApplication {
public static void main(String[] args) {
SpringApplication.run(MainApplication.class, args);
}
}
如果使用第一种@Bean的方式配置,springboot启动会调用MybatisAutoConfiguration.AutoConfiguredMapperScannerRegistrar类的registerBeanDefinitions方法初始化mapper,也就是按照默认路径初始化,所以如果默认路径下没有mapper的interface就会报警告。源代码如下
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
logger.debug("Searching for mappers annotated with @Mapper");
ClassPathMapperScanner scanner = new ClassPathMapperScanner(registry);
try {
if (this.resourceLoader != null) {
scanner.setResourceLoader(this.resourceLoader);
}
//获取路径(Main类所在的包路径)
List packages = AutoConfigurationPackages.get(this.beanFactory);
if (logger.isDebugEnabled()) {
for (String pkg : packages) {
logger.debug("Using auto-configuration base package '{}'", pkg);
}
}
scanner.setAnnotationClass(Mapper.class);
scanner.registerFilters();
scanner.doScan(StringUtils.toStringArray(packages));
} catch (IllegalStateException ex) {
logger.debug("Could not determine auto-configuration package, automatic mapper scanning disabled.", ex);
}
}
所以使用第二种方法配置,可以覆盖springboot的自动配置,就不会报WARN org.mybatis.spring.mapper.ClassPathMapperScanner - No MyBatis mapper was found in…的警告了。
备注:idea里面用 @Autowired注入mapper的时候,会报找不到bean的错误,网上很多解决办法都是关闭idea的注入检查,个人觉得这个办法不好,所以我找到一个另外的办法,用@Resource注入可以解决。