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對(duì)應(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ū)別和選擇建議
方式 | 適用場(chǎng)景 | 優(yōu)點(diǎn) | 缺點(diǎn) |
|---|---|---|---|
| 簡(jiǎn)單的單個(gè)配置項(xiàng) | 簡(jiǎn)單直接 | 配置分散,不易管理 |
| 復(fù)雜的配置組 | 類型安全,集中管理 | 需要?jiǎng)?chuàng)建配置類 |
| 動(dòng)態(tài)獲取配置 | 靈活,可動(dòng)態(tài)獲取 | 類型轉(zhuǎn)換需要手動(dòng)處理 |
推薦使用 @ConfigurationProperties,特別是當(dāng)配置項(xiàng)較多或有關(guān)聯(lián)時(shí),這樣代碼更清晰、易于維護(hù)。
到此這篇關(guān)于springboot的controller中如何獲取applicatim.yml的配置值的文章就介紹到這了,更多相關(guān)springboot controller applicatim.yml配置值內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
教新手使用java如何對(duì)一個(gè)大的文本文件內(nèi)容進(jìn)行去重
用HashSet對(duì)內(nèi)容去重這個(gè)過(guò)程jvm會(huì)內(nèi)存溢出,只能首先將這個(gè)大文件中的內(nèi)容讀取出來(lái),對(duì)每行String的hashCode取模取正整數(shù),可用取模結(jié)果作為文件名,將相同模數(shù)的行寫入同一個(gè)文件,再單獨(dú)對(duì)每個(gè)小文件進(jìn)行去重,最后再合并2021-06-06
Spring-Validation 后端數(shù)據(jù)校驗(yàn)的實(shí)現(xiàn)
這篇文章主要介紹了Spring-Validation 后端數(shù)據(jù)校驗(yàn)的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-07-07
Spring?Boot項(xiàng)目使用WebClient調(diào)用第三方接口的詳細(xì)教程(附實(shí)例代碼)
WebClient是Spring WebFlux模塊提供的一個(gè)非阻塞的基于響應(yīng)式編程的進(jìn)行Http請(qǐng)求的客戶端工具,從Spring5.0開(kāi)始提供,這篇文章主要介紹了Spring?Boot項(xiàng)目使用WebClient調(diào)用第三方接口的相關(guān)資料,需要的朋友可以參考下2025-09-09
實(shí)戰(zhàn)分布式醫(yī)療掛號(hào)系統(tǒng)之設(shè)置微服務(wù)搭建醫(yī)院模塊
這篇文章主要為大家介紹了實(shí)戰(zhàn)分布式醫(yī)療掛號(hào)系統(tǒng)之搭建醫(yī)院設(shè)置微服務(wù)模塊,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-04-04
Java位運(yùn)算和邏輯運(yùn)算的區(qū)別實(shí)例
Java位運(yùn)算和邏輯運(yùn)算的區(qū)別實(shí)例,請(qǐng)參考下面代碼,希望對(duì)你有所幫助2013-02-02
基于Spring定時(shí)任務(wù)的fixedRate和fixedDelay的區(qū)別
這篇文章主要介紹了基于Spring定時(shí)任務(wù)的fixedRate和fixedDelay的區(qū)別,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-10-10
解決java編譯錯(cuò)誤( 程序包javax.servlet不存在javax.servlet.*)
這篇文章主要介紹了解決java編譯錯(cuò)誤的相關(guān)資料,主要解決 程序包javax.servlet不存在javax.servlet.*的問(wèn)題,需要的朋友可以參考下2017-08-08

