Spring Boot 2.0使用WAR打包在Tomcat中外部化属性文件

问题描述 投票:0回答:2

我想创建一个Spring Boot应用程序(打包为WAR),它根据部署的环境自动覆盖某些配置文件。我还希望属性文件在WAR外部。我使用OS Centos和Tomcat作为Web服务器。

我试图在下面的问题Similar question中跟随弗拉基米尔·米特夫的回应。

为了实现这一点,我创建了这个SPRING_CONFIG_ADDITIONAL_LOCATION环境变量。然后在路径中我创建了一个db.properties文件,其中包含我要覆盖的属性。

然后在servlet初始化程序中我把这个配置:

public class ServletInitializer extends SpringBootServletInitializer {
  @Override
  protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
    return application.sources(MyApplication.class).properties("spring.config.name: db");

  }
}

这是另一个需要的类:

@SpringBootApplication
public class MyApplication{
    public static void main(String[] args) {
        System.setProperty("spring.config.name", "db");
        SpringApplication.run(MyApplication.class, args);
    }
}

但是在初始化期间Spring Boot没有找到db.properties文件。

official documentation似乎我必须使用这个“spring.config.additional-location”才能实现我的目标,但我不知道如何。

java spring-boot tomcat configuration war
2个回答
1
投票

在SpringBootServletInitializer中配置为时已晚,您必须在spring应用程序运行之前设置该属性

@SpringBootApplication
public class MyApplication {

    public static void main(String[] args) {
        System.setProperty("spring.config.name", "db");
        SpringApplication.run(MyApplication.class, args);
    }
}

1
投票

你可以试试:

  1. 在[tomcat-server-folder] / bin中创建名为“config”的文件夹
  2. 在config文件夹中创建db.properties文件。 ([Tomcat的服务器的文件夹] /bin/config/db.properties)
  3. 只需在Tomcat的bin目录中创建文件setenv.sh,其中包含以下内容:

JAVA_OPTS =“$ JAVA_OPTS -Dspring.config.name = db”

或者你可以配置文件的具体位置:

JAVA_OPTS =“$ JAVA_OPTS -Dspring.config.location = / opt / app / default.properties,/ opt / app / db.properties”

© www.soinside.com 2019 - 2024. All rights reserved.