【问题标题】:How can I use properties in pom.xml in spring application context xml file?如何在 spring 应用程序上下文 xml 文件中使用 pom.xml 中的属性?
【发布时间】:2017-07-06 15:41:37
【问题描述】:

我有一个与下面给出的类似的 spring 上下文文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <context:property-placeholder
                location="classpath:application.properties, classpath:application-${env}.properties"/>

    <context:annotation-config/>
</beans>

配置profiles的pom.xml的sn-p如下-

        <profile>
            <id>dev</id>
            <properties>
                <env>dev</env>
            </properties>
        </profile>
        <profile>
            <id>test</id>
            <properties>
                <env>test</env>
            </properties>
        </profile>
        <profile>
            <id>prod</id>
            <properties>
                <env>prod</env>
            </properties>
        </profile>

我想在我的 spring 应用程序上下文文件中使用基于所选 maven 配置文件决定的属性“env”。

我该怎么做?

编辑:- 它是一个 Spring Web 应用程序

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>4.1.6.RELEASE</version>
        </dependency>

【问题讨论】:

  • 不,你不想那样做。您不希望有不同的配置文件来构建您的应用程序。这基本上意味着您将在测试时使用不同的工件进行生产,因为您需要重建整个应用程序。而是设置环境变量env,Spring 将简单地替换它。您可以重复使用相同的工件,而不必依赖 Maven。
  • 是的,我们为不同的环境创建了不同的人工制品,但原因更多的是历史性的,这个过程的变化也需要部署脚本的变化。相信我,我也想这样做:) 回到我的问题,我的意图是根据 Maven 配置文件指定的环境切换到不同的环境属性。

标签: java xml spring maven


【解决方案1】:

不直接回答您的问题,但是,如果您可以使用 Spring Boot,我认为您尝试做的事情很容易通过使用 Spring Profiles 解决。

基本上,您避免在 Maven 和 XML 中的多个配置文件中手动编码,让 Spring 为您完成。 Here 是一个基本示例。

【讨论】:

  • 我的项目不是Spring boot,目前还不能带入Spring boot。
  • Profiles 与 Spring Boot 无关,早在 Spring Boot 存在之前,Spring 3.1 就已经支持 Profiles。
猜你喜欢
  • 1970-01-01
  • 2020-06-08
  • 1970-01-01
  • 2020-09-25
  • 2012-01-06
  • 2015-07-06
  • 2015-07-23
  • 1970-01-01
  • 2018-07-16
相关资源
最近更新 更多