springboot加载外部配置文件

时间:2020-04-27
本文章向大家介绍springboot加载外部配置文件,主要包括springboot加载外部配置文件使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

网上搜集和整理如下(自己已验证过)

1.war包运行在独立tomcat下时,如何加载war包外部配置application.properties,以达到每次更新war包而不用更新配置文件的目的。
SpringBoot配置文件可以放置在多种路径下,不同路径下的配置优先级有所不同。
  可放置目录(优先级从高到低)

  • 1.file:./config/ (当前项目路径config目录下);
  • 2.file:./ (当前项目路径下);
  • 3.classpath:/config/ (类路径config目录下);
  • 4.classpath:/ (类路径config下).
  1. 优先级由高到底,高优先级的配置会覆盖低优先级的配置;
  2. SpringBoot会从这四个位置全部加载配置文件并互补配置;

想要满足不更新配置文件的做法一般会采用1 和 2,但是这些对于运行在独立tomcat下的war包并不比作用。
我这里采用的是SpringBoot的Profile配置。
在application.properties中增加如下配置:

spring.profiles.active=test1
  • 再在tomcat根目录下新建一个名为config的文件夹,新建一个名为application-test1.properties的配置文件。
  • 完成该步骤后,Profile配置已经完成了。
  • 然后还需要将刚刚新建的config文件夹添加到tomcat的classpath中。
  • 打开tomcat中catalina.properties文件,在common.loader处添加**${catalina.home}/config**,此处的config即之前新建的文件夹名称。
  • 如此,大功告成。程序启动之后,每次配置文件都会从config/application-test1.properties加载。

2.这里详细介绍下spring.profiles.active

默认配置 src/main/resources/application.properties

app.window.width=500
app.window.height=400

指定具体环境的配置

src/main/resources/application-dev.properties

app.window.height=300

src/main/resources/application-prod.properties

app.window.width=600
app.window.height=700
简单的应用
package com.logicbig.example;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;

@Component
public class ClientBean {
  @Value("${app.window.width}")
  private int width;
  @Value("${app.window.height}")
  private int height;

  @PostConstruct
  private void postConstruct() {
      System.out.printf("width= %s, height= %s%n", width, height);
  }
}
package com.logicbig.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ExampleMain {

  public static void main(String[] args) {
      SpringApplication.run(ExampleMain.class, args);
  }
}
运行
$ mvn spring-boot:run

width= 500, height= 400
$ mvn -Dspring.profiles.active=dev spring-boot:run

width= 500, height= 300
$ mvn -Dspring.profiles.active=prod spring-boot:run

width= 600, height= 700
 

原文地址:https://www.cnblogs.com/guanbin-529/p/12789557.html