Spring Boot 配置文件简介

1. springboot 读取配置的过程

1.1 配置读取顺序

  1. Devtools global settings properties on your home directory (~/.spring-boot-devtools.properties when devtools is active).
  2. @TestPropertySource annotations on your tests.
  3. properties attribute on your tests. Available on @SpringBootTest and the test annotations for testing a particular slice of your application.
  4. Command line arguments.
  5. Properties from SPRING_APPLICATION_JSON (inline JSON embedded in an environment variable or system property).
  6. ServletConfig init parameters.
  7. ServletContext init parameters.
  8. JNDI attributes from java:comp/env.
  9. Java System properties (System.getProperties()).
  10. OS environment variables.
  11. A RandomValuePropertySource that has properties only in random.*.
  12. Profile-specific application properties outside of your packaged jar (application-{profile}.properties and YAML variants).
  13. Profile-specific application properties packaged inside your jar (application-{profile}.properties and YAML variants).
  14. Application properties outside of your packaged jar (application.properties and YAML variants).
  15. Application properties packaged inside your jar (application.properties and YAML variants).
  16. @PropertySource annotations on your @Configuration classes.
  17. Default properties (specified by setting SpringApplication.setDefaultProperties).

1.2 配置读取位置和优先级

当前目录下的/config目录
当前目录
类路径下的/config目录
类路径根目录

2. 两种配置方式

2.1 application.yml 或application.properties

两种配置语法上都可以支持list,map等数据结构,yml可以支持set,application.properties暂时还没找到可以支持set的,个人觉得yml语法更简洁点,看起来会更清晰些。
下面是两个示例
application.properties

#访问的根路径
server.context-path=/springboot
#端口号
server.port=8081
#session失效时间
server.session-timeout=30
#编码
server.tomcat.uri-encoding=utf-8

test.name=kelly
test.password=admin123

yml文件

yaml:
 str: 字符串可以不加引号
 specialStr: "双引号直接输出\n特殊字符"
 specialStr2: '单引号可以转义\n特殊字符'
 flag: false
 num: 666
 Dnum: 88.88
 list:
  - one
  - two
  - two
 set: [1,2,2,3]
 map: {k1: v1, k2: v2}
 positions:
  - name: ITDragon
   salary: 15000.00
  - name: ITDragonBlog
   salary: 18888.88

2.2 配置的读取

读取单个配置

@Value("${test.name}")

读取配置到类中

/**
 * 用户信息
 * @ConfigurationProperties : 被修饰类中的所有属性会和配置文件中的指定值(该值通过prefix找到)进行绑定
 */
@Component
@ConfigurationProperties(prefix = "userinfo")
public class UserInfo {
 
  private String account;
  private Integer age;
  private Boolean active;
  private Date createdDate;
  private Map map;
  private List list;
  private Position position;
 
  // 省略getter,setter,toString方法
}
 
 

3. 参考文献

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html

你可能感兴趣的:(Spring Boot 配置文件简介)