springboot配置文件、属性,优先级顺序

从application.properties说起

  1. 为什么默认是application.properties?
// ConfigFileApplicationListener.java

        private Set<String> getSearchNames() {
            // CONFIG_NAME_PROPERTY值为spring.config.name
            if (this.environment.containsProperty(CONFIG_NAME_PROPERTY)) {
                String property = this.environment.getProperty(CONFIG_NAME_PROPERTY);
                return asResolvedSet(property, null);
            }
            // 添加 names or DEFAULT_NAMES 到 locations 中
            // DEFAULT_NAMES止为application
            return asResolvedSet(ConfigFileApplicationListener.this.names, DEFAULT_NAMES);
        }
  1. application.properties可以改为别的么?

从上面代码可以看出,如果我们通过命令行参数配置了spring.config.name,那么就会去找对应的文件。

$ java -jar myproject.jar --spring.config.name=myproject
  1. 使用spring.profiles.include来激活其他文件:application-db.properties,

application-mq.properties:

spring.profiles.include=db,mq

properties值生效(覆盖)顺序

说明:数值越小,优先级越高

  1. 如果使用了devtools,则 $HOME/.config/spring-boot下的配置文件优先生效。
  2. @TestPropertySource注解的测试
  3. @SpringBootTest中配置的properties
  4. 命令行参数
  5. SPRING_APPLICATION_JSON中的配置。
$ java -Dspring.application.json='{"name":"test"}' -jar myapp.jar
  1. ServletConfig中初始话的参数
  2. ServletContext中初始化的参数
  3. JNDI属性
在java:comp/env中设置
  1. Java系统属性
System.getProperties()

10 操作系统环境变量

  1. RandomValuePropertySource中配置的random.*
  2. jar包外的application-{profile}.propreties/yaml变量
  3. jar包内的application-{profile}.propreties/yaml变量
  4. jar包外的application.propreties/yaml变量
  5. jar包内的application.propreties/yaml变量
  6. @Confiruration类中使用@PropertySoruce注解标注的类。注意,此类变量直到applicationContext刷新后才会被添加到Environment
  7. 默认的属性
通过SpringApplication.setDefaultProperties设置

实践

对于一些重要的参数,可以在项目启动后打印出来,方便监控。

@SpringBootApplication
public class LogTestApplication {

    private static final Logger logger = LoggerFactory.getLogger(LogTestApplication.class);

    public static void main(String[] args) {
        SpringApplication  application = new SpringApplication(LogTestApplication.class);
        application.addListeners(new TestRunListener());
        ConfigurableApplicationContext applicationContext = application.run(args);
        String sqlDb = applicationContext.getEnvironment().getProperty("sql.db");
        logger.info("sql----db:{}",sqlDb);
    }
}

评论

暂无评论