1、属性生效的优先级
- 默认属性(硬编码)
- @PropertySource 绑定的属性
- JAR 包内的 application.properies
- JAR 包外的 application.properies
- JAR 包内的 application-{profiles}.properies
- JAR 包外的 application-{profiles}.properies
- RandomValuePropertySource 随机值属性
- OS 系统环境变量
- Java 系统属性
- JNDI 属性
- ServletContext 初始化参数
- ServletConfig 初始化参数
- SPRING_APPLICATION_JSON 属性
- 命令行参数
- 测试环境properties 属性
- 测试环境@Test
- Devtools 全局配置
上面列出的属性的优先级按序号从低到高,即1优先级最低,17优先级最高
2、动手实验
2.1 默认属性(硬编码)
@SpringBootApplication
public class PropertyTestMainSpringApplication {
public static void main(String[] args) {
SpringApplication springApplication
= new SpringApplication(PropertyTestMainSpringApplication.class);
springApplication.setDefaultProperties(getDefaultProperties());
springApplication.run(args);
}
private static Properties getDefaultProperties() {
Properties defaultProperties = new Properties();
defaultProperties.setProperty(Payment.PAY_TYPE, "alipay from hardcode");
return defaultProperties;
}
}
@Component
public class ResultCommandLineRunner implements
CommandLineRunner , ApplicationRunner, EnvironmentAware {
private Environment environment;
@Override
public void setEnvironment(Environment environment) {
this.environment = environment;
String payType = environment.getProperty(Payment.PAY_TYPE);
System.out.println(payType);
}
@Override
public void run(String... args) throws Exception {
}
@Override
public void run(ApplicationArguments args) throws Exception {
}
}
2.2 @PropertySource
在配置类上加上注解 @PropertySource({"payment.properties"})
@SpringBootApplication
@PropertySource({"payment.properties"})
public class PropertyTestMainSpringApplication {
....
}
文件 resources/payment.properties
pay.type=alipay form payment.properties file
2.3 application.[properties/yml]
2.5