Spring Boot 加载配置多种方式

本文详细介绍了Spring Boot加载配置的多种方式,包括Properties、YAML、XML文件,以及环境变量、系统属性等。讨论了配置资源的加载顺序,并通过实例展示了@Value和@ConfigurationProperties的使用区别,同时演示了如何从XML配置文件中加载配置。
摘要由CSDN通过智能技术生成

在开发Spring Boot应用的时候,也会遇到使用外部配置资源,这些配置资源能够与代码相互配合,避免硬编码 方式,提供应用数据或行为变化的灵活性。也就是说我们需要灵活的用好配置文件,接下来就来介绍获取配置文件的内容的各种姿势。

演示环境

  • IntelliJ IDEA 2018.2.1 (Community Edition)
  • Spring Boot 2.1.1.RELEASE
  • Maven 3.3.9

外部配置资源介绍

1、常见的外部配置资源

在开发的过程中,也许会用到不同的配置资源,这里简单的列一下常见的:

  • Properties 文件
  • YAML 文件
  • XML 文件
  • 环境变量
  • Java 系统属性
  • 命令行参数配置

2、资源的加载顺序

Spring Boot规定了这些外部配置资源的加载的优先级,详情参考官方文档Externalized Configuration小节。这里简要说明一下:

  1. 热加载,也就是根目录下的开发工具全局设置属性(当开发工具激活时为~/.spring-boot-devtools.properties)。
  2. 测试配置,具体指@TestPropertySource注解和@SpringBootTest#properties注解属性值。
  3. 命令行参数。
  4. Servlet 参数ServletConfigServletContext
  5. java:comp/envJNDI属性。
  6. 先系统属性System.getProperties(),再操作系统环境变量。
  7. application-{profile}.properties(先jar外后jar内)。
  8. application.properties(先jar外后jar内)。
  9. @PropertySource引入的配置源。
  10. 通过SpringApplication.setDefaultProperties方法设置的属性。

这里的加载的优先级,高优先级属性源里设置的属性都会覆盖低优先级的相同属性的值。

读取配置

首先准备一个Spring Boot项目,这个就不多说了,接下来就开始演示加载配置的不同方式。

1、从application.properties中加载单个配置

首先我们先编写application.properties配置文件的部分配置:

properties.id = 1
properties.age = 18
properties.student = true
properties.birth = 2018/12/11
properties.array = a,b,c
properties.list = one,two,three

接下来我们编写一个Controller,使用@Value注解和Environment方式来加载我们获取的配置文件的值,并配置一个/properties路径验证其正确性。详见PropertiesController代码:

/**
 * 加载properties文件中的属性的 {@link RestController}
 *
 * @author Jerome Zhu
 */
@RestController
public class PropertiesController implements EnvironmentAware{
   

    @Value("${properties.id}")
    private Integer id;

    @Value("${properties.name:jerome}")
    private String name;

    private Integer age;

    @Value("${properties.student}")
    private Boolean student;

    @Value("${properties.birth}")
    private Date birth;

    @Value("${properties.array}")
    private String[] array;

    @Value("${properties.list}")
    private List<String> list;

    @GetMapping("/properties")
    public Map<String, Object> getProperties() {
   
        Map<String, Object> result = new LinkedHashMap<>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值