spring-boot 应用程序的外部配置

External configuration for spring-boot application

我有一个 spring-boot 应用程序,我想 运行 使用外部配置文件。 当我 运行 它作为 jar(带有嵌入式 servlet 容器)时,一切都很好。 但我想 运行 它在外部 servlet 容器 (Tomcat) 下,这里我有外部配置问题。我尝试了 @PropertySource,但在这种情况下,应用程序仅获取 war 文件配置中不存在的属性:外部配置不会覆盖内部配置。 所以问题是:如何配置将覆盖内部配置的外部配置?

当您将应用程序 运行 作为 jar 时,您可能在当前目录中使用 application.properties 形式的外部配置。但是,"current directory" 在外部 tomcat 中作为 war 部署时不是很有用。即使您知道当前目录是什么,它也很可能是那个 tomcat 中所有应用程序 运行 的相同位置,所以当您 运行 多个应用程序时,那不是会很好地工作。

我们在这里所做的是在我们的应用程序中声明两个 PropertySources

@PropertySources({@PropertySource(value={"classpath:internal.properties"}), @PropertySource(value={"file:${application.properties}"})})

internal.properties 包含 "built in" 个属性的默认值。第二个 PropertySource 是一个包含外部配置的文件。请注意文件名本身是 属性.

我们在应用程序的 Context 元素中(在 tomcat 中)从外部定义它:

<Context docBase="/path/to/your/war/your.war">
    <Parameter name="application.properties" value="/path/to/your/properties/application.properties"/>
</Context>

这允许您在 tomcat 中有多个应用程序 运行,每个应用程序使用它自己的外部属性文件。您甚至可以拥有 相同 应用程序 运行 不同属性的多个实例。

要在部署为 war 文件时外部化 Spring 引导 application.properties,您可以在配置 Spring 引导应用程序时在开头设置 spring.config.location :

public class Application extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder springApplicationBuilder) {
        return springApplicationBuilder
                .sources(Application.class)
                .properties(getProperties());
    }

    public static void main(String[] args) {

        SpringApplicationBuilder springApplicationBuilder = new SpringApplicationBuilder(Application.class)
                .sources(Application.class)
                .properties(getProperties())
                .run(args);
    }

   static Properties getProperties() {
      Properties props = new Properties();
      props.put("spring.config.location", "classpath:myapp1/");
      return props;
   }

有关详细信息,请查看此

Spring 引导提供 many ways 指定您的属性的位置,不需要修改您的来源。

您可以定义 spring.config.location 值,例如:

  • 在您的 tomcat/conf/Catalina/<host> 上下文描述符中:

    <Context>
        <Parameter name="spring.config.location" value="/path/to/application.properties" />
    </Context>
    
  • 作为 tomcat setenv.sh 文件中的 JVM 参数:

    -Dspring.config.location=/path/to/application.properties
    
  • 作为 SPRING_CONFIG_LOCATION 环境变量。

您可以将配置文件文件夹添加到 set Classpath 行 catalina.bat、catalina.sh(如果您想使用哪一个。)或者您可以添加到 setenv.bat/sh 文件。您的配置文件将添加到 war 类路径。

例如;

在 Windows 环境中。

set CLASSPATH=D:\app\conf