小编典典

如何将Spring Boot application.properties外部化为tomcat / lib文件夹

spring-boot

我需要一个免费的,可部署的配置项myapp1.war,它可以从tomcat /
lib文件夹中检索配置文件。由于我在同一个Tomcat上同时存在其他Web应用程序:myapp2.war,myapp3.war,因此需要以下布局:

tomcat/lib/myapp1/application.properties
tomcat/lib/myapp2/application.properties
tomcat/lib/myapp3/application.properties

这样,我可以构建战争文件,而无需在战争内部创建任何属性文件,然后将其部署在任何服务器上。

我已经阅读了Spring文档,但是它解释了以jar运行时如何设置位置:

java -jar myapp.jar --spring.config.location=classpath:/default.properties,classpath:/override.properties

对于多个同时存在的战争文件,我无法弄清楚该如何做。

我想知道这是否可行,还是应该放弃Spring Boot并回到传统的Spring MVC应用程序。


阅读 310

收藏
2020-05-30

共1个答案

小编典典

一个解决方案可能是按照此问题的]建议将application- {profile}
.properties加载为@PropertySource批注,但随后的日志记录系统将无法正常工作,如您在文档中所见。

日志记录系统在应用程序生命周期的早期进行了初始化,因此在通过@PropertySource批注加载的属性文件中找不到此类日志记录属性。

这意味着您在application- {profiles} .properties中的日志记录属性如下:

logging.config=classpath:myapp1/logback.xml
logging.path = /path/to/logs
logging.file = myapp1.log

将被忽略,日志系统将无法正常工作。

为了解决这个问题,我已经在配置应用程序时使用SpringApplicationBuilder.properties()方法在开始时加载属性。在那里,我设置了Spring
Boot用来加载所有application- {profiles} .properties的“ 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;
   }
}

然后,我已将属性文件从src / main / resources移至src / main / resources / myapp1

.
├src
| └main
|   └resources
|     └myapp1
|       └application.properties
|       └application-development.properties
|       └logback.xml
└─pom.xml

在pom.xml中,我必须将嵌入式tomcat库的范围设置为“提供”。另外,要从最终战争中排除src / main / resources /
myapp1中的所有属性文件,并生成免费的,可部署的战争:

    <plugin>
        <artifactId>maven-war-plugin</artifactId>
        <version>2.6</version>
        <configuration>
            <failOnMissingWebXml>false</failOnMissingWebXml>
            <packagingExcludes>
              **/myapp1/
            </packagingExcludes>
        </configuration>
    </plugin>

然后在Tomcat中

├apache-tomcat-7.0.59
 └lib
   ├─myapp1
   |  └application.properties        
   |  └logback.xml
   └─myapp2
     └application.properties
     └logback.xml

现在,我可以生成免配置的war并将其放到apache-tomcat-7.0.59 /
webapps文件夹中。属性文件将使用类路径(对于每个Web应用程序)独立解析:

   apache-tomcat-7.0.59/lib/myapp1
   apache-tomcat-7.0.59/lib/myapp2
   apache-tomcat-7.0.59/lib/myapp3
2020-05-30