在Spring Boot的Controller中获取application.yml配置值,主要有以下几种方式:
1. 使用 @Value注解(最常用)
application.yml 配置
app:
name: "我的应用"
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(推荐用于复杂配置)
创建配置类
@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. 复杂配置示例
application.yml
app:
name: "用户管理系统"
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
对应的配置类
@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. 带默认值的配置
@RestController
@RequestMapping("/api")
public class ConfigController {
// 使用默认值
@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
);
}
}
主要区别和选择建议
| 方式 | 适用场景 | 优点 | 缺点 |
|---|---|---|---|
@Value |
简单的单个配置项 | 简单直接 | 配置分散,不易管理 |
@ConfigurationProperties |
复杂的配置组 | 类型安全,集中管理 | 需要创建配置类 |
Environment |
动态获取配置 | 灵活,可动态获取 | 类型转换需要手动处理 |
推荐使用 @ConfigurationProperties,特别是当配置项较多或有关联时,这样代码更清晰、易于维护。