繁体   English   中英

在 Spring 引导中配置特定的自定义属性文件

[英]Profile specific custom property files in Spring boot

想要检查 Spring 引导是否提供帮助以使用除application.properties文件之外的配置文件。 例如:可以是特定于配置文件的my-custom.properties文件,例如:

  1. 开发配置文件的my-custom-dev.properties
  2. my-custom-uat.properties配置文件的my-custom-uat.properties

编辑:问题是,我有普通的 application-{env}.property 文件,除此之外,还有其他根据其数据内容的属性文件(例如:我想存储在数据库中的日志记录特定属性`db-log.properties,如何使其他文件的配置文件敏感?

您可以将它与活动配置文件一起使用

@Configuration
@PropertySource("classpath:my-custom-${spring.profiles.active}.properties")

除了 application.properties 文件,

可以使用以下约定定义特定于配置文件的属性:application-{profile}.properties。

环境有一组默认配置文件(默认情况下,[默认]),如果没有设置活动配置文件(换句话说,如果没有明确激活配置文件,则加载来自 application-default.properties 的属性)

要运行多个配置文件:

1.application-prod.properties

2.application-dev.properties

mvn spring-boot:run -Dspring-boot.run.profiles=dev,prod

3.application.properties(默认配置文件)

mvn spring-boot:run

4.带有自定义属性文件的命令行参数

spring.config.name - 设置配置文件名称(逗号分隔值) spring.config.location - 设置 Spring Boot 将找到外部化配置文件的位置。

java -jar hello-world.jar --spring.config.name=application,conf --spring.config.location=classpath:/external/properties/,classpath:/com/learn/../../

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-profiles.html

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html#boot-features-external-config-profile-specific-properties

除了application.properties文件之外,您还可以根据需要将其定义为application-{profile}.properties 所选文件在启动时根据您选择的配置文件确定。

是的。 绝对地。 您只需要在开始时提供您想要的配置文件。
例如:

-Dspring.profiles.active=prod 

将使用 application-prod.properties

-Dspring.profiles.active=customer

将使用 application-custom.properties

spring 使用的默认约定是 application-.properties。 所以如果 profile 是 dev 那么它会寻找 application-dev.properties

您也可以使用 bootstrap.properties 文件并可以指定 spring.application.name=my-custom

在这种情况下,spring 将查找 my-custom.properties 文件,当然您可以将它与配置文件 dev,uat 一起使用,因此属性文件名应该是 my-custom-dev.properties。

您也可以将配置文件作为命令行参数以及 -Dspring.config.location=path 文件传递​​。

是的,Spring Boot 可以帮助您。

让 Spring 使用 spring.config.import 属性为您管理不同的属性文件,如下所示:

#application.properties   
spring.config.import=./my-custom.properties

假设 my-custom.properties 文件与 application.properties 位于同一目录中。 这样 Spring 也将能够为您的自定义属性文件管理不同的配置文件,也就是说,如果您激活了“dev”配置文件,将为您加载 my-custom-dev.properties。

请参阅文档

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM