弹簧启动应用程序的外部配置

Ara*_*yan 29 java tomcat spring-boot

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

ci_*_*ci_ 29

application.properties当您将应用程序作为jar运行时,您可能正在使用当前目录中的外部配置.但是,当在外部tomcat中部署为战争时,"当前目录"不是很有用.即使您发现当前目录是什么,它很可能是在该tomcat中运行的所有应用程序的相同位置,因此当您运行多个应用程序时,这将无法正常工作.

我们在这里做的是PropertySources在申请中声明两个:

@PropertySources({@PropertySource(value={"classpath:internal.properties"}), @PropertySource(value={"file:${application.properties}"})})
Run Code Online (Sandbox Code Playgroud)

internal.properties包含"内置"默认值的propeties.第二个PropertySource是包含外部配置的文件.请注意文件的名称本身是如何属性.

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

<Context docBase="/path/to/your/war/your.war">
    <Parameter name="application.properties" value="/path/to/your/properties/application.properties"/>
</Context>
Run Code Online (Sandbox Code Playgroud)

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

  • 感谢您的答复。是的,这个配置会起作用,正如我在我的问题中提到的,我尝试了这个解决方案。这个方案的缺点是外部配置不会覆盖内部配置。我的问题是如何设置外部配置的优先级? (2认同)

Dan*_*ora 20

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

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;
   }
Run Code Online (Sandbox Code Playgroud)

有关详情,请这个解决方案.


Raf*_*ves 17

Spring Boot提供了许多指定属性位置的方法,不需要修改源代码.

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