spring boot 获取配置文件中的值
在 Spring Boot 中,你可以使用 @Value
注解或 @ConfigurationProperties
注解来获取配置文件(如 application.properties 或 application.yml)中的值。
使用
@Value
注解:@Value("${property.key}")
private String propertyKey;
在上述代码中,
${property.key}
是配置文件中的属性键。如果property.key
的值是 "value",那么propertyKey
变量的值就会是 "value"。使用
@ConfigurationProperties
注解:首先,需要在启动类(带有
@SpringBootApplication
的类)或其他配置类上加上@EnableConfigurationProperties
注解并指定配置类:@SpringBootApplication
@EnableConfigurationProperties(SomeProperties.class)
public class Application {
// ...
}
然后,创建一个类(例如:SomeProperties)来绑定配置项:
@ConfigurationProperties(prefix = "some")
public class SomeProperties {
private String key;
// getter and setter
}
如果你在配置文件中有这样的配置项:
some.key=value
,那么通过SomeProperties
类的对象就可以获取到该值。
以上两种方式都可以用来获取配置文件中的值,选择哪种方式主要取决于具体情况。@Value
更适合于只需获取少数几个配置项的情况,而 @ConfigurationProperties
则更适合于需要把相关配置项组织起来的情况。