Spring Boot应用程序.properties文件继承另一个属性文件

14
我有一个属性文件中的一些属性,我想将它们继承到应用程序属性中。请问在Spring Boot中是否可能实现?
类似这样:
application.properties
----------------------
extends = otherproperty.properties
property1 = value1
property2= value2
property3 = value3

otherproperty.properties
------------------------
property4=value4
property5 = value5
当 Spring Boot 应用程序加载时,我希望使用 @Value 注释,所有 5 个属性都应该被加载并且可用。Spring Boot 会自动选择类路径中的 application.properties 文件,我不需要任何 applicaitoncontext xml 或任何属性加载器代码。
提前感谢。

你想要在一个属性文件中继承另一个属性文件,还是想要将它们合并?换句话说,两个属性文件都可以包含property6属性吗,还是它们没有重叠? - Jiri Tousek
1
我只想继承,它们不重叠。 - skumar
如果属性重叠会发生什么?应用程序中的application.properties属性值会被其他property.properties覆盖吗? - saket satpute
3个回答

14

你可以使用配置文件来实现。

使用application.properties文件,你可以为每个配置文件定义一个文件,如下所示:

application.properties # This is the main file
spring.profiles=p1,p2,p3
prop-main=hi

application-p1.properties # This is the file with p1 properties
property1=patata

application-p2.properties # This is the file with p2 properties
property2=catsup

application-p3.properties # This is the file with p3 properties
property3=helloworld

Spring将翻译文件并像这样使用:

application.properties # This is the main file
spring.profiles=p1,p2,p3
prop-main=hi
property1=patata
property2=catsup
property3=helloworld

这个解决方案是可行的,但每个组必须保留一个单独的文件。

还有另一种方法,您可以使用单个YAML文件代替多个properties文件。只需将 application.properties 替换为 application.yml 并执行如下操作:

server:
    address: 192.168.1.100
---
spring:
    profiles: development
server:
    address: 127.0.0.1
---
spring:
    profiles: production
server:
    address: 192.168.1.120

您可以阅读参考文档,了解有关使用YAML替代Properties以及多配置文件的YAML文档的更多信息。


11

对于我而言,在 application.properties 文件中,spring.profiles.include=p1,p2,p3 的方法有效。


1
spring.profiles.include在application-dev.properties中也能起作用吗? 假设我有两个开发环境dev1和dev2,它们有许多共同的属性。 我想要一个devbase.properties文件,我想要将其包含在dev1和dev2中这是可能的吗? - Paritosh Gupta

3

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接