1. 程式人生 > 程式設計 >springboot 使用yml配置檔案給靜態變數賦值教程

springboot 使用yml配置檔案給靜態變數賦值教程

宣告:

此處需求是修改封裝的clickhouseUtil資料查詢引擎連線工具類。由於此類中的方法都是靜態方法。連線地址等引數需要根據不同環境改變。例如開發下地址,測試下地址,生產地址等,所有通過配置檔案來獲取不同環境下的配置引數,但是使用的方法是靜態的,所有不能使用一般情況下的@value直接給變數賦值,需要用到spring 屬性的set方法來給靜態變數賦值,然後靜態方法使用靜態變數即可

方法:

第一步:在yml檔案中配置需要的引數

clickhouse:
 address: jdbc:clickhouse://172.20.xxx.xxx:8123
 username: default
 password: xxxxx
 db: marketing
 socketTimeout: 600000

第二步:

類上一定要先註明@Component註解,在程式啟動是自動載入,否則靜態引數仍舊獲取不到配置檔案的值

建立靜態變數

給靜態變數set方法上新增@Value()

 @Value("${clickhouse.address}")
 public void setClickhouseAddress(String address) {
  ClickHouseUtil.clickhouseAddress = address;
 }

最後在靜態方法中使用即可

@Component
public class ClickHouseUtil {
 
 private static String clickhouseAddress;
 
 private static String clickhouseUsername;
 
 private static String clickhousePassword;
 
 private static String clickhouseDB;
 
 private static Integer clickhouseSocketTimeout;
 
 @Value("${clickhouse.address}")
 public void setClickhouseAddress(String address) {
  ClickHouseUtil.clickhouseAddress = address;
 }
 @Value("${clickhouse.username}")
 public void setClickhouseUsername(String username) {
  ClickHouseUtil.clickhouseUsername = username;
 }
 @Value("${clickhouse.password}")
 public void setClickhousePassword(String password) {
  ClickHouseUtil.clickhousePassword = password;
 }
 @Value("${clickhouse.db}")
 public void setClickhouseDB(String db) {
  ClickHouseUtil.clickhouseDB = db;
 }
 @Value("${clickhouse.socketTimeout}")
 public void setClickhouseSocketTimeout(Integer socketTimeout) {
  ClickHouseUtil.clickhouseSocketTimeout = socketTimeout;
 }
 
 
 public static Connection getConn() {
 
  ClickHouseConnection conn = null;
  ClickHouseProperties properties = new ClickHouseProperties();
  properties.setUser(clickhouseUsername);
  properties.setPassword(clickhousePassword);
  properties.setDatabase(clickhouseDB);
  properties.setSocketTimeout(clickhouseSocketTimeout);
  ClickHouseDataSource clickHouseDataSource = new ClickHouseDataSource(clickhouseAddress,properties);
  try {
   conn = clickHouseDataSource.getConnection();
   return conn;
  } catch (SQLException e) {
   e.printStackTrace();
  }
 
  return null;
 }
 
 public static List<JSONObject> exeSql(String sql){
  log.info("cliockhouse 執行sql:" + sql);
  Connection connection = getConn();
  try {
   Statement statement = connection.createStatement();
   ResultSet results = statement.executeQuery(sql);
   ResultSetMetaData rsmd = results.getMetaData();
   List<JSONObject> list = new ArrayList();
   while(results.next()){
    JSONObject row = new JSONObject();
    for(int i = 1;i<=rsmd.getColumnCount();i++){
     row.put(rsmd.getColumnName(i),results.getString(rsmd.getColumnName(i)));
    }
    list.add(row);
   }
 
   return list;
  } catch (SQLException e) {
   e.printStackTrace();
  }
  return null;
 }
 
}

以上這篇springboot 使用yml配置檔案給靜態變數賦值教程就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。