配置文件读取方式 低高
1. @PropertySource@Configuration类上的注释。请注意,Environment在刷新应用程序上下文之前,不会将此
类属性源添加到中。现在配置某些属性(如logging.*和spring.main.*在刷新开始之前先读取)为时已晚。
a. 会和约定的配置文件形成互补
b. 一定要指定.properties配置
@PropertySource("classpath:appSource.properties")
2. 默认属性(通过设置指定SpringApplication.setDefaultProperties)。
a. 会和约定的配置文件形成互补
public class ExternConfigurationApplication {
public static void main(String[] args) throws IOException {
SpringApplication springApplication = new SpringApplication(ExternConfigurationApplication.class);
// 创建Properties
Properties properties = new Properties();
// 通过当前类的ClassLoader
InputStream is= ExternConfigurationApplication.class.getClassLoader()
.getResourceAsStream("app.properties");
// 将输入流读取成properties
properties.load(is);
springApplication.setDefaultProperties(properties);
springApplication.run(args);
}
}
3. 配置数据(例如application.properties文件)
a. 约定配置文件
4. 操作系统环境变量。
a. 会使约定配置文件失效
b. 1.idea
c. 2.windows
set spring.config.location=D:\config/
java ‐jar 03_extern_configuration‐0.0.1‐SNAPSHOT.jar
5. Java系统属性(System.getProperties())。
a. 会使约定配置文件失效
b. idea
c. 命令行java属性
java ‐Dspring.config.location=D:\config\application‐java.properti
es ‐jar 03_extern_configuration‐0.0.1‐SNAPSHOT.jar
6. 的JNDI属性java:comp/env。
7. ServletContext 初始化参数。
ServletContext 的配置标签需要写到 web‐app (根标签)中 ,具体如下:
<context‐param>
<param‐name>spring.config.location</param‐name>
<param‐value>xxx.properties</param‐value>
</context‐param>
8. ServletConfig 初始化参数。
ServletConfig 的配置标签需要写到 Servlet 标签中,标签如下:
<init‐param>
<param‐name>spring.config.location</param‐name>
<param‐value>xxx.properties</param‐value>
</init‐param>
9. 来自的属性SPRING_APPLICATION_JSON(嵌入在环境变量或系统属性中的嵌入式JSON)。
10. 命令行参数。
a. 会使约定配置文件失效
java ‐jar configuration_file‐0.0.1‐SNAPSHOT.jar ‐‐spring.config.location=D:/application.properties
11. properties测试中的属性。可用于测试应用程序的特定部分@SpringBootTest的测试注释和注释。
12. @TestPropertySource 测试中的注释。
a. 用在单元测试上的
@SpringBootTest
@TestPropertySource("classpath:appSource.properties")
class ExternConfigurationApplicationTests {
@Value("${server.port}")
private String port;
@Test
void contextLoads() {
System.out.println(port);
}
}
13. $HOME/.config/springboot当devtools处于活动状态时,目录中的Devtools全局设置属性。