Java 属性文件的Spring Boot外部配置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43020491/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring boot external configuration of property file
提问by turoni
I have a spring boot application that I can package in a war that I want to deploy to different environments. To automate this deployment it'd be easier to have the configuration file externalized.
我有一个 Spring Boot 应用程序,我可以将它打包到我想部署到不同环境的战争中。要自动执行此部署,将配置文件外部化会更容易。
Currently everything works fine with a application.properties file in src/main/resources. Then I use ′mvn install′ to build a war deployable to tomcat. But I would like to use a .yml file that does not need to be present on mvn install but that would be read from during deployment of the war and is in the same or a directory relative to my war.
目前,在 src/main/resources 中的 application.properties 文件中一切正常。然后我使用“mvn install”来构建一个可部署到 tomcat 的 war。但我想使用一个 .yml 文件,该文件不需要出现在 mvn install 上,但会在战争部署期间读取,并且位于与我的战争相同或相对的目录中。
24. externalized configurationshows where spring boot will look for files and 72.3 Change the location of external properties of an applicationgives more detail on how to configure this but I just do not understand how to translate this to my code.
24. 外部化配置显示了 spring boot 将在哪里查找文件和72.3 更改应用程序的外部属性的位置提供了有关如何配置它的更多详细信息,但我只是不明白如何将其转换为我的代码。
My application class looks like this: package be.ugent.lca;
我的应用程序类如下所示: package be.ugent.lca;
Updated below
Do I need to add a @PropertySource to this file? How would I refer to a certain relative path?
我需要在这个文件中添加一个 @PropertySource 吗?我将如何引用某个相对路径?
I feel like it's probably documented in there as most spring boot documentation but I just don't understand how they mean me to do this.
我觉得它可能作为大多数 spring 引导文档记录在那里,但我只是不明白他们是如何让我这样做的。
EDIT
编辑
Not sure if this should be a separate issue but I think it's still related.
Upon setting the os variable the error of yaml file not found went away. Yet I still get the same error again as when I had no application .properties or .yml file.
Application now looks like this:
不确定这是否应该是一个单独的问题,但我认为它仍然相关。
设置 os 变量后,找不到 yaml 文件的错误消失了。然而,当我没有应用程序 .properties 或 .yml 文件时,我仍然再次遇到相同的错误。应用程序现在看起来像这样:
@Configuration
**@PropertySource("file:${application_home}/application.yml")**
@ComponentScan({"be.ugent.lca","be.ugent.sherpa.configuration"})
@EnableAutoConfiguration
@EnableSpringDataWebSupport
public class Application extends SpringBootServletInitializer{
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
The application_home OS variable
application_home 操作系统变量
$ echo $application_home
C:\Masterproef\clones\la15-lca-web\rest-service\target
My application.yml file(part it complains about):
我的 application.yml 文件(它抱怨的部分):
sherpa:
package:
base: be.ugent.lca
Error upon java -jar *.war All variations upon:
java -jar *.war 上的错误:所有变体:
Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'sherpa.package.base' in string value "${sherpa.package.base}"
at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:174)
at org.springframework.util.PropertyPlaceholderHelper.replacePlaceholders(PropertyPlaceholderHelper.java:126)
at org.springframework.core.env.AbstractPropertyResolver.doResolvePlaceholders(AbstractPropertyResolver.java:204)
at org.springframework.core.env.AbstractPropertyResolver.resolveRequiredPlaceholders(AbstractPropertyResolver.java:178)
at org.springframework.context.support.PropertySourcesPlaceholderConfigurer.resolveStringValue(PropertySourcesPlaceholderConfigurer.java:172)
at org.springframework.beans.factory.support.AbstractBeanFactory.resolveEmbeddedValue(AbstractBeanFactory.java:808)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1027)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1014)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:545)
... 142 more
采纳答案by lo?c
Using external properties files
使用外部属性文件
The answer lies in the Spring Boot Docs, I'll try to break it down for you.
答案在 Spring Boot Docs 中,我会尽力为您分解。
First of all, no you should not use @PropertySource
when working with Yaml configuration, as mentioned here under the Yaml shortcomings:
首先,@PropertySource
在使用 Yaml 配置时不应该使用,正如这里提到的Yaml 缺点:
YAML files can't be loaded via the @PropertySource annotation. So in the case that you need to load values that way, you need to use a properties file.
无法通过 @PropertySource 注释加载 YAML 文件。因此,如果您需要以这种方式加载值,则需要使用属性文件。
So, how to load propery files? That is explained here Application Property Files
那么,如何加载属性文件呢?此处解释了应用程序属性文件
One is loaded for you: application.yml
, place it in one of the directories as mentioned in the link above. This is great for your general configuration.
为您加载了一个:application.yml
,将其放在上面链接中提到的目录之一中。这非常适合您的一般配置。
Now for your environment specific configuration (and stuff like passwords) you want to use external property files, how to do that is also explained in that section :
现在对于您要使用外部属性文件的环境特定配置(以及密码之类的东西),该部分还解释了如何执行此操作:
If you don't like application.properties as the configuration file name you can switch to another by specifying a spring.config.name environment property. You can also refer to an explicit location using the spring.config.location environment property (comma-separated list of directory locations, or file paths).
如果您不喜欢 application.properties 作为配置文件名,您可以通过指定 spring.config.name 环境属性切换到另一个。您还可以使用 spring.config.location 环境属性(以逗号分隔的目录位置列表或文件路径)引用显式位置。
So you use the spring.config.location
environment property.
Imagine you have an external config file: application-external.yml
in the conf/ dir under your home directory, just add it like this:
-Dspring.config.location=file:${home}/conf/application-external.yml
as a startup parameter of your JVM.
If you have multiple files, just seperate them with a comma. Note that you can easily use external properties like this to overwrite properties, not just add them.
所以你使用spring.config.location
环境属性。假设您有一个外部配置文件:application-external.yml
在您的主目录下的 conf/ 目录中,只需像这样添加它:
-Dspring.config.location=file:${home}/conf/application-external.yml
作为您的 JVM 的启动参数。如果您有多个文件,只需用逗号分隔它们。请注意,您可以轻松地使用这样的外部属性来覆盖属性,而不仅仅是添加它们。
I would advice to test this by getting your application to work with just your internal application.yml file , and then overwrite a (test) property in your external properties file and log the value of it somewhere.
我建议通过让您的应用程序仅使用您的内部 application.yml 文件来测试这一点,然后在您的外部属性文件中覆盖一个(测试)属性并在某处记录它的值。
Bind Yaml properties to objects
将 Yaml 属性绑定到对象
When working with Yaml properties I usually load them with @ConfigurationProperties
, which is great when working with for example lists or a more complex property structure. (Which is why you should use Yaml properties, for straightforward properties you are maybe better of using regular property files). Read this for more information: Type-Safe Configuration properties
使用 Yaml 属性时,我通常使用 加载它们@ConfigurationProperties
,这在使用例如列表或更复杂的属性结构时非常有用 。(这就是您应该使用 Yaml 属性的原因,对于简单的属性,您最好使用常规属性文件)。阅读此内容以获取更多信息:类型安全配置属性
Extra: loading these properties in IntelliJ, Maven and JUnit tests
额外:在 IntelliJ、Maven 和 JUnit 测试中加载这些属性
Sometimes you want to load these properties in your maven builds or when performing tests. Or just for local development with your IDE
有时您想在 Maven 构建中或执行测试时加载这些属性。或者只是为了使用您的 IDE 进行本地开发
If you use IntelliJfor development you can easily add this by adding it to your Tomcat Run Configuration : "Run" -> "Edit Configurations" , select your run configuration under "Tomcat Server" , check the Server tab and add it under "VM Options".
如果您使用IntelliJ进行开发,您可以通过将其添加到 Tomcat 运行配置中来轻松添加它:“运行”->“编辑配置”,在“Tomcat 服务器”下选择您的运行配置,检查服务器选项卡并将其添加到“VM”下选项”。
To use external configuration files in your Maven build: configure the maven surefire plugin like this in your pom.xml:
要在Maven 构建中使用外部配置文件:在 pom.xml 中像这样配置 maven surefire 插件:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<argLine>-Dspring.config.location=file:${home}/conf/application-external.yml
</configuration>
</plugin>
When running JUnit testsin IntelliJ:
在 IntelliJ 中运行JUnit 测试时:
- Run → Edit Configurations
- Defaults → JUnit
- add VM Options ->
-ea -Dspring.config.location=file:${home}/conf/application-external.yml
- 运行 → 编辑配置
- 默认值 → JUnit
- 添加虚拟机选项 ->
-ea -Dspring.config.location=file:${home}/conf/application-external.yml
回答by developer
Yes, you need to use @PropertySource
as shown below.
是的,您需要使用@PropertySource
如下所示。
The important point here is that you need to provide the application_home
property (or choose any other name) as OS environment variable or System property or you can pass as a command line argumentwhile launching Spring boot. This property tells where the configuration file (.properties
or .yaml
) is exactly located (example: /usr/local/my_project/
etc..)
这里的重点是您需要提供application_home
属性(或选择任何其他名称)作为操作系统环境变量或系统属性,或者您可以在启动 Spring boot 时作为命令行参数传递。此属性告诉配置文件(.properties
或.yaml
)的确切位置(例如:/usr/local/my_project/
等..)
@Configuration
@PropertySource("file:${application_home}config.properties")//or specify yaml file
@ComponentScan({"be.ugent.lca","be.ugent.sherpa.configuration"})
@EnableAutoConfiguration
@EnableSpringDataWebSupport
public class Application extends SpringBootServletInitializer{
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
回答by vinoth Kumar
Use below code in your boot class:
在您的引导类中使用以下代码:
@PropertySource({"classpath:omnicell-health.properties"})
use below code in your controller:
在您的控制器中使用以下代码:
@Autowired
private Environment env;
回答by vishal lakhyani
One of the easiest way to use externalized property file using system environment variable is, in application.properties file you can use following syntax:
使用系统环境变量使用外部化属性文件的最简单方法之一是,在 application.properties 文件中,您可以使用以下语法:
spring.datasource.url = ${OPENSHIFT_MYSQL_DB_HOST}:${OPENSHIFT_MYSQL_DB_PORT}/"nameofDB"
spring.datasource.username = ${OPENSHIFT_MYSQL_DB_USERNAME}
spring.datasource.password = ${OPENSHIFT_MYSQL_DB_PORT}
Now, declare above used environment variables,
现在,声明上面使用的环境变量,
export OPENSHIFT_MYSQL_DB_HOST="jdbc:mysql://localhost"
export OPENSHIFT_MYSQL_DB_PORT="3306"
export OPENSHIFT_MYSQL_DB_USERNAME="root"
export OPENSHIFT_MYSQL_DB_PASSWORD="123asd"
This way you can use different value for same variable in different environments.
这样你就可以在不同的环境中为相同的变量使用不同的值。