SpringBoot如何讀取配置檔案引數並全域性使用
阿新 • • 發佈:2020-01-07
這篇文章主要介紹了SpringBoot如何讀取配置檔案引數並全域性使用,文中通過示例程式碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
前言:
讀取配置檔案引數的方法:@Value("${xx}")註解。但是@Value不能為static變數賦值,而且很多時候我們需要將引數放在一個地方統一管理,而不是每個類都賦值一次。
正文:
注意:一定要給類加上@Component 註解
application.xml
test: app_id: 12345 app_secret: 66666 is_active: true
統一讀取配置檔案引數:
package com.example.demo.config; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; @Configuration public class YxConfig { public static String appId; public static String appSecret; public static boolean isActive; @Value("${test.app_id}") public void setAppId(String param) { appId = param; } @Value("${test.app_secret}") public void setAppSecret(String param) { appSecret = param; } @Value("${test.is_active}") public void setIsActive(boolean param) { isActive = param; } }
測試類:
@RunWith(SpringRunner.class) @SpringBootTest public class YxConfigTest { @Test public void test() { System.out.print("app_id:" + YxConfig.appId + "; "); System.out.print("app_secret:" + YxConfig.appSecret+ "; "); System.out.print("is_active:" + YxConfig.isActive); } }
結果:
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。