Spring Boot提供了多種方式來獲取配置文件的屬性值:
@Value
注解:在需要獲取屬性值的字段上,使用@Value("${property.name}")
注解來注入屬性值。例如:@Value("${my.property}")
private String myProperty;
@ConfigurationProperties
注解:在一個(gè)配置類上使用@ConfigurationProperties(prefix = "prefix")
注解,將屬性值注入到該類的字段中。例如:@ConfigurationProperties(prefix = "my")
public class MyConfig {
private String property;
// getter和setter方法
}
此時(shí),需要在配置文件中使用my.property=value
的格式來設(shè)置屬性值。
Environment
對(duì)象:通過Spring的Environment
對(duì)象來獲取配置屬性。例如:@Autowired
private Environment env;
public void getProperty() {
String property = env.getProperty("my.property");
}
以上是Spring Boot中常用的獲取配置屬性值的方式。根據(jù)具體的情況,選擇適合的方式來獲取屬性值。