spring-boot 应用程序的外部配置 [英] External configuration for spring-boot application

查看:45
本文介绍了spring-boot 应用程序的外部配置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a spring-boot application which I want to run with external configuration file. When I run it as jar (with embedded servlet container), everything is fine. But I want to run it under external servlet container (Tomcat) and here i have problem with external configuration. I have tried a @PropertySource, but in this case application gets only properties absent in war file configuration: external configuration doesn't override internal configuration. So the question: how can I configure external configuration which will override internal configuration?

推荐答案

当您将应用程序作为一个罐子.但是,在外部 tomcat 中作为战争部署时,当前目录"并不是很有用.即使您找出当前目录是什么,对于在该 tomcat 中运行的所有应用程序来说,它很可能位于相同的位置,因此当您运行多个应用程序时,这不会很好地工作.

You're probably using external configuration in the form of application.properties in the current directory when you're running your application as a jar. However, "current directory" isn't very useful when deploying as a war in an external tomcat. Even if you find out what the current directory is, it's most likely the same location for all applications running in that tomcat, so when you're running more than one application, that's not going to work very well.

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

What we do here is this declare two PropertySources on our application:

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

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

internal.properties contains "built in" default values for propeties. The second PropertySource is a file containing external configuration. Note how the name of the file is itself a property.

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

We define this externally in the Context element of our application (in tomcat):

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

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

This allows you to have multiple applications running in tomcat, each application using it's own external properties file. You can even have multiple instances of the same application running with different properties.

这篇关于spring-boot 应用程序的外部配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆