前言
配置文件一般存放一些系统变量或用户变量,例如数据库数据源的配置。它可以实现在不改变程序源代码的情况下修改程序的变量的值。通过配置文件可以使程序开发变得更加灵活。接下来我将介绍几种常见的在 SpringBoot 中获取配置文件的方式。
我的示例配置文件(userinfo.yml)位置如下:

1 2 3 4 5 6 7 8 9 10 11 12
| my-profile: name: grape age: 6
users: - name: 张三 age: 20 - name: 李四 age: 21 - name: 王五 age: 22
|
通过 @value
读取简单信息
通过在变量前加上注解 @value("${xxx}")
可以将配置信息注入到变量中
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| package com.pushihao.controller;
import com.pushihao.bean.YmlConfigFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.PropertySource; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;
@RestController @PropertySource(value = {"classpath:userinfo.yml"},encoding="UTF-8",factory = YmlConfigFactory.class) public class UserinfoController { @Value("${my-profile.name}") private String name;
@Value("${my-profile.age}") private String age;
@RequestMapping("/u1") public String u1() { return "name:" + name + "|age:" + age; } }
|
注意:
@PropertySource 注解可以指定要读取的配置文件的位置。不写此注解默认读取SpringBoot默认配置文件application.properties/application.yml/application.yaml。
因为 @PropertySource 注解默认是读取 properties 文件,所以如果是读取 properties 文件,注解可以写成 @PropertySource(value = {“classpath:userinfo.properties”},encoding=”UTF-8”)。
本例中读取的是 yml 文件,需要重写 DefaultPropertySourceFactory...