站点图标 AI技术聚合

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配置文件给静态变量赋值教程就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持aitechtogether.com。

退出移动版