0
点赞
收藏
分享

微信扫一扫

8.1、Spring Boot 属性配置

船长_Kevin 2022-12-29 阅读 162


1、属性生效的优先级

  1. 默认属性(硬编码)
  2. @PropertySource 绑定的属性
  3. JAR 包内的 application.properies
  4. JAR 包外的 application.properies
  5. JAR 包内的 application-{profiles}.properies
  6. JAR 包外的 application-{profiles}.properies
  7. RandomValuePropertySource 随机值属性
  8. OS 系统环境变量
  9. Java 系统属性
  10. JNDI 属性
  11. ServletContext 初始化参数
  12. ServletConfig 初始化参数
  13. SPRING_APPLICATION_JSON 属性
  14. 命令行参数
  15. 测试环境properties 属性
  16. 测试环境@Test
  17. 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


举报

相关推荐

0 条评论