如何使用Maven配置文件设置Spring Active配置文件
我有一个使用maven作为构建工具的应用程序。
我正在使用Maven配置文件从不同的配置文件设置不同的属性。
我想做的是将maven中的所有活动配置文件也移植到spring活动配置文件中,以便我可以在bean签名(@profile
)中引用它们。但是我不确定该怎么做。
例如:考虑以下Maven设置
<profiles> <profile>
<id>profile1</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
</properties>
</profile>
<profile>
<id>profile2</id>
<properties>
</properties>
</profile>
<profile>
<id>development</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
</properties>
</profile>
<profile>
<id>production</id>
<properties>
</properties>
</profile>
</profiles>
假设我在未指定任何其他配置文件的情况下运行maven,而我希望spring具有profile1
和 development作为活动配置文件。
回答:
你必须过滤应用程序的资源,例如属性文件,其中包含要在spring激活的配置文件的信息。
例如
spring.profile = ${mySpringProfile}
并为每个配置文件定义此变量的值(mySpringProfile
)。
在构建期间,将根据当前活动配置文件中定义的值对其进行过滤。
然后,在应用程序的引导过程中,你将根据该文件选择适当的配置文件(由于你没有向我们提供更多信息,因此无法为你提供更多帮助,但这很容易。
注意:我找不到在maven中获取当前活动配置文件的方法(类似于project.profiles.active,其中包含你的-P值),这就是为什么你必须为每个配置文件设置新变量的原因。
注意2:如果你正在运行Web应用程序,则不要使用此中间文件,而应在web.xml中过滤该值
<context-param> <param-name>spring.profiles.active</param-name>
<param-value>${mySpringProfile}</param-value>
</context-param>
注意3:这实际上是一种不好的做法,你应该在运行时使用系统属性设置配置文件
以上是 如何使用Maven配置文件设置Spring Active配置文件 的全部内容, 来源链接: utcz.com/qa/424555.html