解决springboot整合druid遇到的坑springboot整合druid的坑
项⽬环境
springboot 2.1.6.RELEASE
jdk 1.8
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="/POM/4.0.0" xmlns:xsi="/2001/XMLSchema-instance"
xsi:schemaLocation="/POM/4.0.0 /xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId&st</groupId>
<artifactId>page</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>page</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<druid.version>1.1.10</druid.version>
</properties>
<dependencies>spring boot选择题
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>${druid.version}</version>
</dependency>
<!-- mvnrepository/batis.spring.boot/mybatis-spring-boot-starter -->
<dependency>
<groupId&batis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.1</version>
</dependency>
<!-- mvnrepository/artifact/com.github.pagehelper/pagehelper-spring-boot-starter -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.5</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.28</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
</project>
server:
port: 8001
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
druid:
mysql:
name: mysql
url: jdbc:mysql://localhost:3306/user?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
driver-class-name: sql.cj.jdbc.Driver
username: root
password: root
# 下⾯为连接池的补充设置,应⽤到上⾯所有数据源中
# 初始化⼤⼩,最⼩,最⼤
initialSize: 5
minIdle: 5
maxActive: 20
# 配置获取连接等待超时的时间
maxWait: 60000
#      oracle:
#        name: oracle
#        url: jdbc:oracle:thin:@127.0.0.1:1521:ORCL
#        username: zs
#        password: 123456
#        initialSize: 5
#        minIdle: 5
#        maxActive: 20
#        maxWait: 60000
mybatis:
mapper-locations:
- classpath*:mapper/*.xml
配置数据源时有个问题:username,password,url,driver-class-name既可以配在spring.datasource下⾯,也可以配置在spring.datasource.druid下⾯。
如果直接配在spring.datasource下⾯,当配置多个数据源时,不⽅便指定前缀。
如果配置在spring.datasource.druid下⾯,需要在配置类(@Configuration)中获取相应的值。如果不配置会报不到url,driver-class-name的错。
DruidDataSourceConfiguration配置类
fig;
import com.alibaba.druid.filter.stat.StatFilter;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import com.alibaba.druid.wall.WallConfig;
import com.alibaba.druid.wall.WallFilter;
import org.apache.ibatis.session.SqlSessionFactory;
batis.spring.SqlSessionFactoryBean;
batis.spring.SqlSessionTemplate;
batis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import t.annotation.Bean;
import t.annotation.Configuration;
import io.support.PathMatchingResourcePatternResolver;
@Configuration
@MapperScan(sqlSessionTemplateRef = "mysqlSqlSessionTemplate",basePackages = "st.page.dao")
public class DruidDataSourceConfiguration {
private static final String PRE="spring.sql.";
@Value("${"+PRE+"url}")
private String url;
@Value("${"+PRE+"driver-class-name}")
private String driverClassName;
@Value("${"+PRE+"username}")
private String username;
@Value("${"+PRE+"password}")
private String password;
@Value("${"+PRE+"initialSize}")
private int initialSize;
@Value("${"+PRE+"maxActive}")
private int maxActive;
@Value("${"+PRE+"minIdle}")
private int minIdle;
@Value("${"+PRE+"maxWait}")
private long maxWait;
@Bean("mysqlDataSource")
public DruidDataSource mysqlDataSource(){
DruidDataSource druidDataSource = new DruidDataSource();
druidDataSource.setUrl(url);
druidDataSource.setUsername(username);
druidDataSource.setDriverClassName(driverClassName);
druidDataSource.setPassword(password);
druidDataSource.setInitialSize(initialSize);
druidDataSource.setMinIdle(minIdle);
druidDataSource.setMaxActive(maxActive);
druidDataSource.setMaxWait(maxWait);
return druidDataSource;
}
@Bean("mysqlSqlSessionFactory")
public SqlSessionFactory mysqlSqlSessionFactory() throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(mysqlDataSource());
//使⽤xml的⽅式,如果不配置会⼀直不到sql
//默认使⽤注解的⽅式
sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
.getResources("classpath:mapper/*.xml"));
Object();
}
@Bean("mysqlSqlSessionTemplate")
public SqlSessionTemplate mysqlSqlSessionTemplate()throws Exception{
return new SqlSessionTemplate(mysqlSqlSessionFactory());
}
@Bean
public ServletRegistrationBean druidServlet() {
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");        //控制台管理⽤户,加⼊下⾯2⾏进⼊druid后台就需要登录
//servletRegistrationBean.addInitParameter("loginUsername", "admin");
//servletRegistrationBean.addInitParameter("loginPassword", "admin");
return servletRegistrationBean;
}
@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;
}
@Bean
public StatFilter statFilter(){
StatFilter statFilter = new StatFilter();
statFilter.setLogSlowSql(true); //slowSqlMillis⽤来配置SQL慢的标准,执⾏时间超过slowSqlMillis的就是慢。
statFilter.setMergeSql(true); //SQL合并配置
statFilter.setSlowSqlMillis(1000);//slowSqlMillis的缺省值为3000,也就是3秒。
return statFilter;
}
@Bean
public WallFilter wallFilter(){
WallFilter wallFilter = new WallFilter();
//允许执⾏多条SQL
WallConfig config = new WallConfig();
config.setMultiStatementAllow(true);
wallFilter.setConfig(config);
return wallFilter;
}
}
这⾥有个坑:不到xml中的sql
org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): st.page.dao.UserDao.findById
出现上⾯问题的原因有很多。
例如:
1:检查xml⽂件所在package名称是否和Mapper interface所在的包名⼀⼀对应;
2:检查xml的namespace是否和xml⽂件的package名称⼀⼀对应;
3:检查⽅法名称是否对应;
如果不是上⾯这⼏种问题:
在配置类中添加setMapperLocations(),并且指定xml的位置
@Bean("mysqlSqlSessionFactory")
public SqlSessionFactory mysqlSqlSessionFactory() throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(mysqlDataSource());
//使⽤xml的⽅式,如果不配置会⼀直不到sql
//默认使⽤注解的⽅式
sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
.getResources("classpath:mapper/*.xml"));
Object();
}
springboot整合alibaba/druid
⼀,⽤快速建⽴建⽴spring boot项⽬
springboot 版本号为1.5.12和选择相对应的⼯具(如版本不⼀致会导致运⾏错误)
<!-- mvnrepository/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.9</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
⼆添加yml⽂件
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://localhost:3306/dept?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull    driver-class-name: sql.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
#  数据源其他配置
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
#  配置监控统计拦截的filters,去掉后监控界⾯sql⽆法统计,'wall'⽤于防⽕墙
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: Sql=true;druid.stat.slowSqlMillis=500
三建⽴config包
3.1 建⽴dataSourcesConfig类
package fig;
import com.alibaba.druid.pool.DruidDataSource;

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。