1.在pom.xml文件中加入Druid的依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.21</version>
</dependency>
2.在配置文件application.yml,切换Druid数据源(type)
spring:
datasource:
username: root
password: admin
url: jdbc:mysql://localhost:3306/mybatis?userUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
driver-class-name: com.mysql.cj.jdbc.Driver
#指定数据源
type: com.alibaba.druid.pool.DruidDataSource
#指定数据源
type: com.alibaba.druid.pool.DruidDataSource
#Spring Boot 默认是不注入这些属性值的,需要自己绑定
#druid 数据源专有配置
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,stat:监控统计、log4j:日志记录、wall:防御sql注入
#如果允许时报错 java.lang.ClassNotFoundException: org.apache.log4j.Priority
#则导入 log4j 依赖即可,Maven 地址: https://mvnrepository.com/artifact/log4j/log4j
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
3.配置中用到了log4j,所以log4j要导入相关依赖
4.然后编写一个配置类,将配置类和配置文件绑定在一起(这样配置文件里的属性才能生效)
关键:@Configuration、@Bean、@ConfigurationProperties(prefix = "spring.datasource")
@Configuration
public class DruidConfig {
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druidDataSource(){
return new DruidDataSource();
}
}
然后在类中配置其他功能
//后台监控:web.xml ServletRegistrationBean
//因为SprinBboot内置了servlet容器,所以没有web.xml,替代方法:ServletRegistrationBean
@Bean
public ServletRegistrationBean statViewServlet(){
ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");
//后台需要有人登陆,账号密码配置
HashMap<String, String> initParameters = new HashMap<>();
//增加配置
//登录的key是固定的loginUsername、loginPassword
initParameters.put("loginUsername", "admin");
initParameters.put("loginPassword", "123");
//允许谁可以访问
//为空的话就是所有都可访问
initParameters.put("allow", "localhost");
//禁止谁访问
//initParameters.put("kzj", "ip地址");//禁止本ip访问
bean.setInitParameters(initParameters);//设置初始化参数
return bean;
}
//filter
//配置一个web监控的filter
@Bean
public FilterRegistrationBean webStatFilter(){
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(new WebStatFilter());
Map<String, String> initParameters = new HashMap<>();
//这些东西不进行统计
initParameters.put("exclusions", "*.js,*.css,/druid/*");
//配置filter过滤所有请求
bean.setUrlPatterns(Arrays.asList("/*"));
//可以过滤那些请求呢?
bean.setInitParameters(initParameters);
return bean;
}
可在test函数中测试是否配置成功
@SpringBootTest
class SpringBoot06DataMybatisApplicationTests {
@Autowired
DataSource dataSource;
@Test
void contextLoads() throws SQLException {
System.out.println(dataSource.getClass());
Connection connection = dataSource.getConnection();
System.out.println(connection);
connection.close();
}
}