springboot profile 配置读取

原文地址:https://blog.csdn.net/lazycheerup/article/details/51915185?utm_source=blogxgwz2

具体做法:

  • 不同环境的配置设置一个配置文件,例如:dev环境下的配置配置在application-dev.properties中;prod环境下的配置配置在application-prod.properties中。
  • 在application.properties中指定使用哪一个文件

      1、application-dev.properties(dev环境下的配置)

profile = dev_envrimont

       2、application-prod.properties(prod环境下的配置)

 profile = prod_envrimont

       3、application.properties

spring.data.mongodb.uri=mongodb://192.168.22.110:27017/myfirstMongodb

#spring.profiles.active
spring.profiles.active=dev

4、Controller

@Autowired
private Environment env;
   
@RequestMapping("/testProfile")
public String testProfile(){
   return env.getProperty("profile");
}

测试

a.上述代码执行后的结果是:dev_envrimont和mongodb://192.168.22.110:27017/myfirstMongodb

b.如果application.properties的配置改为:spring.profiles.active=prod, 则结果是: prod_envrimont

c.如果application.properties的配置改为:spring.profiles.active=prod,而application.properties
  中也配置了profile=xxx(不管该配置配置在spring.profiles.active=prod的上方还是下方),  这个时候结果是:  
prod_envrimont

d.如果application.properties的配置改为:spring.profiles.active=prod, 而application.properties中也配置了profile=xxx(不管该配 置配置在spring.profiles.active=prod 的上方还是下方),

但是application-prod.properties删掉了profile = prod_envrimont, 这个时候结果是: xxx

结论:

  • 各个环境公共的配置写在application.properties中
  • 各个模块独有的配置配置在自己的application-{xxx}.properties文件中
  • 程序读取的时候优先读取application.properties中选中的profile的配置,若读不到才会从application.properties去读

猜你喜欢

转载自blog.csdn.net/justlpf/article/details/83414722
今日推荐