关于java:springboot配置文件属性优先级顺序

5次阅读

共计 1885 个字符,预计需要花费 5 分钟才能阅读完成。

从 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);
    }
}
正文完
 0