配置类(配置信息在类中)

  1. @Configuration
  2. public class DruidDBConfig {
  3. @Bean
  4. public ServletRegistrationBean druidServlet() {
  5. ServletRegistrationBean reg = new ServletRegistrationBean();
  6. reg.setServlet(new StatViewServlet());
  7. reg.addUrlMappings("/druid/*");
  8. reg.addInitParameter("loginUsername", "druid");
  9. reg.addInitParameter("loginPassword", "123456");
  10. reg.addInitParameter("resetEnable", "false");
  11. return reg;
  12. }
  13. @Bean
  14. public FilterRegistrationBean filterRegistrationBean() {
  15. FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
  16. filterRegistrationBean.setFilter(new WebStatFilter());
  17. Map<String, String> initParams = new HashMap<String, String>();
  18. initParams.put("exclusions", "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*");
  19. filterRegistrationBean.setInitParameters(initParams);
  20. filterRegistrationBean.addUrlPatterns("/*");
  21. return filterRegistrationBean;
  22. }
  23. }

配置类(配置信息在yml文件中)

配置类

  1. @Configuration
  2. public class DataSourceConfig {
  3. /**
  4. * *注册一个StatViewServlet
  5. * *@return
  6. */
  7. @Bean
  8. @ConfigurationProperties("datasource.druid.stat-view-servlet")
  9. public ServletRegistrationBean druidStatViewServle(){
  10. return new ServletRegistrationBean(new StatViewServlet());
  11. }
  12. @Bean
  13. @ConfigurationProperties("datasource.druid.web-stat-filter")
  14. public FilterRegistrationBean druidStatFilter() {
  15. return new FilterRegistrationBean(new WebStatFilter());
  16. }
  17. }

yml文件

  1. dataSource:
  2. druid:
  3. stat-view-servlet:
  4. #是否启用StatViewServlet(监控页面)默认值为false(考虑到安全问题默认并未启动,如需启用建议设置密码或白名单以保障安全)
  5. enabled: true
  6. url-mappings: "/druid2/*"
  7. # 该参数为map, key必须保持该格式
  8. init-parameters:
  9. loginUsername: "admin"
  10. loginPassword: "admin"
  11. resetEnable: "false"
  12. # WebStatFilter配置,说明请参考Druid Wiki,配置_配置WebStatFilter
  13. web-stat-filter:
  14. #是否启用StatFilter默认值false
  15. enabled: true
  16. url-patterns: "/*"
  17. # 该参数为map, key必须保持该格式
  18. init-parameters:
  19. exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"

注意事项

  1. init-parameters在对应实体类中是map,spring读取yml后会直接进行put,所以loginUsername,loginPassword等不可以写成login-username,login-password格式
  2. 在设置resetEnable(是否可以重置)后, 页面上方的重置按钮还是可以点击,并返回已重置.但是实际上没有进行操作