提示信息

spring boot 获取配置文件中的值

沉世 已关注

在 Spring Boot 中,你可以使用 @Value 注解或 @ConfigurationProperties 注解来获取配置文件(如 application.properties 或 application.yml)中的值。

  1. 使用 @Value 注解:

    1. @Value("${property.key}")
    2. private String propertyKey;

    在上述代码中,${property.key} 是配置文件中的属性键。如果 property.key 的值是 "value",那么 propertyKey 变量的值就会是 "value"。

  2. 使用 @ConfigurationProperties 注解:

    首先,需要在启动类(带有 @SpringBootApplication 的类)或其他配置类上加上 @EnableConfigurationProperties 注解并指定配置类:

    1. @SpringBootApplication
    2. @EnableConfigurationProperties(SomeProperties.class)
    3. public class Application {
    4. // ...
    5. }

    然后,创建一个类(例如:SomeProperties)来绑定配置项:

    1. @ConfigurationProperties(prefix = "some")
    2. public class SomeProperties {
    3. private String key;
    4. // getter and setter
    5. }

    如果你在配置文件中有这样的配置项:some.key=value,那么通过 SomeProperties 类的对象就可以获取到该值。

以上两种方式都可以用来获取配置文件中的值,选择哪种方式主要取决于具体情况。@Value 更适合于只需获取少数几个配置项的情况,而 @ConfigurationProperties 则更适合于需要把相关配置项组织起来的情况。

    遇到难题? "AI大模型GPT4.0、GPT" 是你的私人解答专家! 点击按钮去提问......
沉世 关注 已关注

最近一次登录:2023-09-21 10:41:05   

暂时还没有签名,请关注我或评论我的文章
×
免费图表工具,画流程图、架构图