SpringBoot 读取配置文件

目录

一 属性文件和加载方式

二 属性来源和优先级

三 属性文件优先级

四 参考文档


一 属性文件和加载方式

application.yml 文件

test:
  user:
    username : lisi
    age: 5

1.1 @Value 方式

import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Data
@Component
public class PropertiesConfig {

    @Value("${test.user.username}")
    private String username;

    @Value("${test.user.age}")
    private String age;
}

1.2 @ConfigurationProperties 方式

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Data
@Component
@ConfigurationProperties(prefix = "test.user")
public class PropertiesConfig1 {

    private String username;

    private String age;
}

1.3 如果加载一个文件 test.yml

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Data
@Component
@PropertySource(value = "classpath:test.yml")
@ConfigurationProperties(prefix = "test.user")
public class PropertiesConfig2 {

    private String username;

    private String age;
}

二 属性来源和优先级

1 命令行参数

2 java:comp/env 里的 JNDI 属性

3 JVM 系统属性

4 操作系统环境变量

5 随机生成的带 random.* 前缀的属性

6 应用程序以外的 application.properties 或者 application.yml 文件

7 打包在应用程序内的 application.properties 或者 application.yml 文件

8 通过 @PropertySource 标注的属性源

9 默认属性

       上面9条优先级由高到底,任何在高优先级属性源里面设置的属性都会覆盖低优先级的相同属性。例如,命令行参数会覆盖其他属性源里的属性。

三 属性文件优先级

application.properties 和 application.yml 文件能放在一下四个地方

1 外置,在相对于应用程序运行目录的 /config 子目录里。

2 外置,在应用程序运行的目录里。

3 内置,在 config 包内。

4 内置,在 Classpath 根目录。

       上面4条属性加载优先级从高到底,也就是说,/config 子目录里面的 application.properties 会覆盖应用程序 Classpath 里的application.properties;此外,在同一个优先级位置同时有 application.properties 和 application.yml ,application.yml 里面的属性会覆盖 application.properties 里面的属性。

四 参考文档

https://docs.spring.io/spring-boot/docs/1.5.4.RELEASE/reference/htmlsingle/#common-application-properties

发布了67 篇原创文章 · 获赞 64 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/jack1liu/article/details/102648580