@SpringBootTest
public class MainApplicationTests {
@Autowired
DataSource dataSource;
@Test
public void bootTest(){
//获取数据源信息 class com.alibaba.druid.pool.DruidDataSource
System.out.println(dataSource.getClass());
}
}
编写配置类 Config
package com.boot.config;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
import java.util.HashMap;
@Configuration
public class DruidConfig {
@Bean
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource druidDataSource(){
return new DruidDataSource() ;
}
//后台监控
@Bean
public ServletRegistrationBean statViewServlet(){
ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(),"/druid/*");
//后台登录设置
HashMap<String,String> initParameters = new HashMap<>();
initParameters.put("loginUsername","admine"); //loginUsername、loginUsername 是固定的
initParameters.put("loginUsername","123456");
//允许某个用户访问
initParameters.put("allow","localhost");
bean.setInitParameters(initParameters); //设置初始化参数
return bean;
}
//设置一个拦截
@Bean
public FilterRegistrationBean webStatFilter(){
FilterRegistrationBean<Filter> bean = new FilterRegistrationBean<>();
bean.setFilter(new WebStatFilter());
HashMap<String,String> initParameters = new HashMap<>();
initParameters.put("exclusions","*.js,druid/*"); //哪些请求不拦截
bean.setInitParameters(initParameters);
return bean;
}
}