1、引入依赖:

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.8</version>
</dependency>

2、生成DruidDataSource,配置servlet与filter

@Configuration
public class DruidConfiguration {
    @Bean
    @ConfigurationProperties(prefix="spring.datasource")
    public DataSource dataSource() {
        return new DruidDataSource();
    }

    //配置Druid监控
    //1.配置StatViewServlet
    @Bean
    public ServletRegistrationBean statViewServlet() {
        ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        Map<String, String> param = new HashMap<>();
        param.put("loginUsername", "admin");
        param.put("loginPassword", "123");
        param.put("allow", ""); //默认就是允许所有访问
//        param.put("deny", "127.0.0.1");
        bean.setInitParameters(param);
        return bean;
    }

    //配置Druid监控
    //2.配置WebStatFilter
    @Bean
    public FilterRegistrationBean webStatFilter() {
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(new WebStatFilter());
        Map<String, String> param = new HashMap<>();
        param.put("exclusions", "*.js,*.css,/druid/*");
        bean.setInitParameters(param);
        bean.setUrlPatterns(Arrays.asList("/*"));
        return bean;
    }
}

自定义数据源配置application.yml:

spring:
  datasource:
    driverClassName: com.mysql.jdbc.Driver
    url: jdbc:mysql://47.94.145.253:3306/cms?useUnicode=true&characterEncoding=UTF-8&useSSL=false
    username: root
    password: root
    poolPreparedStatements: false
    maxActive: 50
    initialSize: 0
    minIdle: 5
    logAbandoned: true
    removeAbandoned: true
    removeAbandonedTimeout: 600
    maxWait: 10000
    timeBetweenEvictionRunsMillis: 10000
    numTestsPerEvictionRun: 10
    minEvictableIdleTimeMillis: 30000
    validationQuery: select 1
    keepAlive: true
    testWhileIdle: false
    testOnBorrow: false
    testOnReturn: false
    # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,‘wall’用于防火墙
    filters: stat,wall,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500