1. 外部配置

Spring Boot支持外部配置,以便可以在不同的环境中使用相同的应用程序代码。可以使用properties文件,YAML文件,环境变量或命令行参数进行外部配置。可以使用@Value注解将属性值直接注入到定义的bean中,可通过Spring的Environment抽象访问该属性,或者通过@ConfigurationProperties绑定到结构化对象。

Spring Boot使用一个特别的PropertySource顺序,旨在允许合理地覆盖值。属性按以下顺序选择:

1) 在HOME目录设置的Devtools全局属性,如当devtools设置可用时,该目录为~/.spring-boot-devtools.properties;

2) 单元测试中的@TestPropertySource注解

3) 单元测试中的@SpringBootTest#properties注解属性

4) 命令行参数

5) SPRING_APPLICATION_JSON中的属性(在环境变量或系统属性中内嵌的JSON)

6) ServletConfig初始化参数

7) ServletContext初始化参数

8) java:comp/env中的JNDI属性

9) Java系统属性,即System.getProperties()

10) 操作系统环境变量

11) RandomValuePropertySource, 仅在random.*中有属性

12) jar包外的Profile-specific应用属性,如application-(profile).properties和YAML变体

13) jar包内的Profile-specific应用属性,如application.properties和YAML变体

14) jar包外的应用属性,如application.properties和YAML变体

15) jar包内的应用属性,如application.properties和YAML变体

16) 在@Configuration类中的@PropertySource注解

17) 默认属性(通过SpringApplication.setDefaultProperties指定)

例:假设开发@Component并使用一个name属性:

import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component public class MyBean { @Value("${name}") private String name; }
View Code

相关文章: