首頁 > 軟體

springboot載入複雜的yml檔案獲取不到值的解決方案

2022-03-24 10:00:11

springboot載入yml檔案獲不到值

今天使用spring boot讀取yml檔案,這種多層巢狀的竟然無法讀取到(value註解spring.redis.pool.max.wait),即便加上全名也不行,然後網上搜到的內容也未曾滿意,很多文章內容都是一樣且重複的.最後放棄了查詢,突發奇想之下解決了這個問題.

本文旨在如何讀取多層巢狀的yml檔案,希望能幫到眾位.

以下是程式碼:

package com.boot.config;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
@Configuration
@ConfigurationProperties(prefix = "spring.redis;pool.max;pool.min")
@PropertySource(value = "classpath:redis.yml")
public class RedisConfiguration implements ApplicationListener<ApplicationEvent> {
	@Value("${host}")
	private String host;
	@Value("${port}")
	private Long port;
	@Value("${timeout}")
	private Long timeout;
	@Value("${database}")
	private Long database;
	
	@Value("${wait}")
	private Long poolMaxWait;
	@Value("${idle}")
	private Long poolMaxIdle;
	@Value("${idle}")
	private Long poolMinIdle;
	@Value("${active}")
	private Long poolMaxActive;
	public void onApplicationEvent(ApplicationEvent event) {
        // 列印屬性
		System.out.println("============= redisConnect ================");
		System.out.println(this.toString());
    }
	@Override
    public String toString() {
	    return "RedisConfiguration [host=" + host + ", port=" + port + ", timeout=" + timeout
	            + ", database=" + database + ", poolMaxWait=" + poolMaxWait + ", poolMaxIdle="
	            + poolMaxIdle + ", poolMinIdle=" + poolMinIdle + ", poolMaxActive=" + poolMaxActive
	            + "]";
    }
}
#多層設定
spring:
	redis:
		database: 0
		host: localhost
		port: 6379
		timeout: 0
		pool:
		   max:
			  active: 8
			  wait: -1
			  idle: 8
		   min:
			  idle: 0

紀錄檔列印如下所示:

============= redisConnect ================
RedisConfiguration [host=localhost, port=6379, timeout=0, database=0, poolMaxWait=-1, poolMaxIdle=0, poolMinIdle=0, poolMaxActive=8]

獲取不到yml組態檔指定的值

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication 
public class App {
     public static void main(String[] args) {
        SpringApplication app = new SpringApplication(App.class);
        ConfigurableApplicationContext context = app.run(args);
        System.out.println(context.getEnvironment().getProperty("jdbc.pwd"));  
        context.close();
   }
}

apllication.yml 放置在classpath路徑下

jdbc:
 pwd: 123456  #冒號和數位之間有一個空格,沒有否則獲取失敗,pwd前面有縮排兩個字元

ps:版本spring-4.3.2-release,springboot-1.4

以上為個人經驗,希望能給大家一個參考,也希望大家多多支援it145.com。


IT145.com E-mail:sddin#qq.com