springboot的controller中如何獲取applicatim.yml的配置值
在Spring Boot的Controller中獲取application.yml配置值,主要有以下幾種方式:
1. 使用@Value注解(最常用)
application.yml 配置
app: name: "我的應(yīng)用" version: "1.0.0" max-users: 100 enabled: true timeout: 30000
Controller 中使用
@RestController
@RequestMapping("/api")
public class ConfigController {
@Value("${app.name}")
private String appName;
@Value("${app.version}")
private String appVersion;
@Value("${app.max-users}")
private int maxUsers;
@Value("${app.enabled}")
private boolean enabled;
@Value("${app.timeout}")
private long timeout;
@GetMapping("/config")
public Map<String, Object> getConfig() {
Map<String, Object> config = new HashMap<>();
config.put("name", appName);
config.put("version", appVersion);
config.put("maxUsers", maxUsers);
config.put("enabled", enabled);
config.put("timeout", timeout);
return config;
}
}2. 使用@ConfigurationProperties(推薦用于復(fù)雜配置)
創(chuàng)建配置類
@Configuration
@ConfigurationProperties(prefix = "app")
@Data
public class AppConfig {
private String name;
private String version;
private int maxUsers;
private boolean enabled;
private long timeout;
private List<String> whitelist;
private Map<String, String> endpoints;
}在Controller中注入使用
@RestController
@RequestMapping("/api")
public class ConfigController {
@Autowired
private AppConfig appConfig;
@GetMapping("/config")
public AppConfig getConfig() {
return appConfig;
}
@GetMapping("/info")
public String getAppInfo() {
return appConfig.getName() + " v" + appConfig.getVersion();
}
}3. 使用Environment接口
@RestController
@RequestMapping("/api")
public class ConfigController {
@Autowired
private Environment environment;
@GetMapping("/env-config")
public Map<String, Object> getEnvConfig() {
Map<String, Object> config = new HashMap<>();
config.put("name", environment.getProperty("app.name"));
config.put("version", environment.getProperty("app.version"));
config.put("maxUsers", environment.getProperty("app.max-users", Integer.class));
config.put("timeout", environment.getProperty("app.timeout", Long.class, 5000L));
return config;
}
}4. 復(fù)雜配置示例
application.yml
app:
name: "用戶管理系統(tǒng)"
version: "2.1.0"
database:
url: "jdbc:mysql://localhost:3306/mydb"
username: "admin"
pool-size: 20
security:
jwt-secret: "my-secret-key"
token-expire: 3600
cors-origins:
- "http://localhost:3000"
- "https://example.com"
features:
enable-cache: true
enable-notification: false對應(yīng)的配置類
@Configuration
@ConfigurationProperties(prefix = "app")
@Data
public class AppConfig {
private String name;
private String version;
private DatabaseConfig database;
private SecurityConfig security;
private FeaturesConfig features;
@Data
public static class DatabaseConfig {
private String url;
private String username;
private int poolSize;
}
@Data
public static class SecurityConfig {
private String jwtSecret;
private int tokenExpire;
private List<String> corsOrigins;
}
@Data
public static class FeaturesConfig {
private boolean enableCache;
private boolean enableNotification;
}
}Controller中使用
@RestController
@RequestMapping("/api")
public class SystemController {
@Autowired
private AppConfig appConfig;
@GetMapping("/system-info")
public Map<String, Object> getSystemInfo() {
return Map.of(
"appName", appConfig.getName(),
"databaseUrl", appConfig.getDatabase().getUrl(),
"corsOrigins", appConfig.getSecurity().getCorsOrigins(),
"enableCache", appConfig.getFeatures().isEnableCache()
);
}
}5. 帶默認(rèn)值的配置
@RestController
@RequestMapping("/api")
public class ConfigController {
// 使用默認(rèn)值
@Value("${app.unknown-property:default-value}")
private String unknownProperty;
@Value("${app.retry-count:3}")
private int retryCount;
@GetMapping("/default-values")
public Map<String, Object> getWithDefaults() {
return Map.of(
"unknownProperty", unknownProperty,
"retryCount", retryCount
);
}
}主要區(qū)別和選擇建議
方式 | 適用場景 | 優(yōu)點 | 缺點 |
|---|---|---|---|
| 簡單的單個配置項 | 簡單直接 | 配置分散,不易管理 |
| 復(fù)雜的配置組 | 類型安全,集中管理 | 需要創(chuàng)建配置類 |
| 動態(tài)獲取配置 | 靈活,可動態(tài)獲取 | 類型轉(zhuǎn)換需要手動處理 |
推薦使用 @ConfigurationProperties,特別是當(dāng)配置項較多或有關(guān)聯(lián)時,這樣代碼更清晰、易于維護。
到此這篇關(guān)于springboot的controller中如何獲取applicatim.yml的配置值的文章就介紹到這了,更多相關(guān)springboot controller applicatim.yml配置值內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
教新手使用java如何對一個大的文本文件內(nèi)容進行去重
用HashSet對內(nèi)容去重這個過程jvm會內(nèi)存溢出,只能首先將這個大文件中的內(nèi)容讀取出來,對每行String的hashCode取模取正整數(shù),可用取模結(jié)果作為文件名,將相同模數(shù)的行寫入同一個文件,再單獨對每個小文件進行去重,最后再合并2021-06-06
Spring-Validation 后端數(shù)據(jù)校驗的實現(xiàn)
這篇文章主要介紹了Spring-Validation 后端數(shù)據(jù)校驗的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-07-07
Spring?Boot項目使用WebClient調(diào)用第三方接口的詳細(xì)教程(附實例代碼)
WebClient是Spring WebFlux模塊提供的一個非阻塞的基于響應(yīng)式編程的進行Http請求的客戶端工具,從Spring5.0開始提供,這篇文章主要介紹了Spring?Boot項目使用WebClient調(diào)用第三方接口的相關(guān)資料,需要的朋友可以參考下2025-09-09
實戰(zhàn)分布式醫(yī)療掛號系統(tǒng)之設(shè)置微服務(wù)搭建醫(yī)院模塊
這篇文章主要為大家介紹了實戰(zhàn)分布式醫(yī)療掛號系統(tǒng)之搭建醫(yī)院設(shè)置微服務(wù)模塊,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-04-04
基于Spring定時任務(wù)的fixedRate和fixedDelay的區(qū)別
這篇文章主要介紹了基于Spring定時任務(wù)的fixedRate和fixedDelay的區(qū)別,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-10-10
解決java編譯錯誤( 程序包javax.servlet不存在javax.servlet.*)
這篇文章主要介紹了解決java編譯錯誤的相關(guān)資料,主要解決 程序包javax.servlet不存在javax.servlet.*的問題,需要的朋友可以參考下2017-08-08

