Java之SpringBoot自定義配置與整合Druid
SpringBoot配置檔案
優先順序
前面SpringBoot基礎有提到,關於SpringBoot配置檔案可以是properties
或者是yaml
格式的檔案,但是在SpringBoot載入application
配置檔案時是存在一個優先順序的。優先順序如下:
file:./config/ ==> 專案路徑下的config目錄下
file:./ ==> 專案路徑下
classpath:/config/ ==> 資源路徑下的config目錄下
classpath:/ ==> 專案路徑下
yaml的多文件配置
yaml可以通過---
達到在一個檔案中寫入多套配置檔案的效果
server:
port: 8081
spring:
profiles: dev
---
server:
port: 8082
spring:
profiles: test
@canditionalon註解,Spring底層的註解, 用於判斷是否符合條件,符合條件才會自動裝配。
擴充套件SpringMVC
新增自定義檢視解析器
ViewResolver 試圖解析器,實現了該介面的類都可以稱作試圖解析器
candidateViews 候選檢視,getBestView 得到最優檢視
其中有getCandidateViews方法,先遍歷所有的檢視解析器,之後封裝成view物件,新增到candidateViews候選檢視解析器陣列中。
自定檢視解析器需要實現ViewResolver介面並重寫resolveViewName方法
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
@Bean
public ViewResolver myViewResolver(){
return new MyViewResolver();
}
public static class MyViewResolver implements ViewResolver {
@Override
public View resolveViewName(String viewNaem, Locale locale) throws Exception {
return null;
}
}
}
想自定義其他功能也是同理,按格式寫好元件交給SpringBoot自動裝配即可。
自定義DruidDataSources
About Druid
Druid:https://github.com/alibaba/druid/
Druid是alibaba開源平臺上一個資料庫連線池實現,結合了C3P0,DBCP等DB池的優點,同時也有Web監控介面。
Druid可以很好的監控DB池連線和SQL執行的情況,為監控而生的DB連線池。
SpringBoot2.0以上預設使用Hikari資料來源,下面記錄下如何用SpringBoot整合配置Druid
新增依賴
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.21</version>
</dependency>
配置資料來源
因為SpringBoot2.0以上預設使用Hikari資料來源,所以需要用 spring.datasource.type 指定資料來源。
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://localhost:3306/springboot?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource # 自定義資料來源
可以起一個測試類檢視
@Test
public void druidTest() throws SQLException {
//檢視預設資料來源
System.out.println(dataSource.getClass());
//獲得資料庫連線
Connection connection = dataSource.getConnection();
System.out.println(connection);
//close
connection.close();
}
其他配置
具體其他配置可參考官方文件,簡單列舉一些:
#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
關於監控的配置是Druid特點。比如可配置log4j以及自帶wall防止sql注入
Druid配置類
一般在config包下,與自定義元件類似,通過@ConfigurationProperties註解與配置檔案中datasource的配置繫結並交給SpringBoot自動裝配。
@Configuration
public class DruidConfig {
/*
將自定義的 Druid資料來源新增到容器中,不再讓 Spring Boot 自動建立
繫結全域性配置檔案中的 druid 資料來源屬性到 com.alibaba.druid.pool.DruidDataSource從而讓它們生效
@ConfigurationProperties(prefix = "spring.datasource"):作用就是將 全域性配置檔案中
字首為 spring.datasource的屬性值注入到 com.alibaba.druid.pool.DruidDataSource 的同名引數中
*/
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druidDataSource() {
return new DruidDataSource();
}
}
測試類
@Test
public void druidTest() throws SQLException {
//檢視預設資料來源
System.out.println(dataSource.getClass());
//獲得資料庫連線
Connection connection = dataSource.getConnection();
System.out.println(connection);
//close
connection.close();
DruidDataSource druidDataSource = (DruidDataSource) dataSource;
System.out.println("druidDataSource 資料來源最大連線數:" + druidDataSource.getMaxActive());
System.out.println("druidDataSource 資料來源初始化連線數:" + druidDataSource.getInitialSize());
}
資料來源監控
還是在同一個配置類檔案中寫入,這裡對於審計或者滲透測試中的重點其實就是使用者名稱密碼了和其訪問限制了
package com.zh1z3ven.hellospringboot.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;
import java.util.Map;
@Configuration
public class DruidConfig {
/*
將自定義的 Druid資料來源新增到容器中,不再讓 Spring Boot 自動建立
繫結全域性配置檔案中的 druid 資料來源屬性到 com.alibaba.druid.pool.DruidDataSource從而讓它們生效
@ConfigurationProperties(prefix = "spring.datasource"):作用就是將 全域性配置檔案中
字首為 spring.datasource的屬性值注入到 com.alibaba.druid.pool.DruidDataSource 的同名引數中
*/
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druidDataSource() {
return new DruidDataSource();
}
//配置 Druid 監控管理後臺的Servlet;
//內建 Servlet 容器時沒有web.xml檔案,所以使用 Spring Boot 的註冊 Servlet 方式
@Bean
public ServletRegistrationBean statViewServlet() {
ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
// 這些引數可以在 com.alibaba.druid.support.http.StatViewServlet
// 的父類 com.alibaba.druid.support.http.ResourceServlet 中找到
Map<String, String> initParams = new HashMap<>();
initParams.put("loginUsername", "admin"); //後臺管理介面的登入賬號
initParams.put("loginPassword", "123456"); //後臺管理介面的登入密碼
//後臺允許誰可以訪問
//initParams.put("allow", "localhost"):表示只有本機可以訪問
//initParams.put("allow", ""):為空或者為null時,表示允許所有訪問
initParams.put("allow", "");
//deny:Druid 後臺拒絕誰訪問
//initParams.put("kuangshen", "192.168.1.20");表示禁止此ip訪問
//設定初始化引數
bean.setInitParameters(initParams);
return bean;
}
}
配置完後重啟專案,訪問測試
監控過濾器filter配置
//配置 Druid 監控 之 web 監控的 filter
//WebStatFilter:用於配置Web和Druid資料來源之間的管理關聯監控統計
@Bean
public FilterRegistrationBean webStatFilter() {
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(new WebStatFilter());
//exclusions:設定哪些請求進行過濾排除掉,從而不進行統計
Map<String, String> initParams = new HashMap<>();
initParams.put("exclusions", "*.js,*.css,/druid/*,/jdbc/*");
bean.setInitParameters(initParams);
//"/*" 表示過濾所有請求
bean.setUrlPatterns(Arrays.asList("/*"));
return bean;
}