【问题标题】:Maven how to set properties visible in javaMaven如何设置在java中可见的属性
【发布时间】:2014-02-27 21:12:07
【问题描述】:

这是我在 pom.xml 中的个人资料:

<!-- Production Profile -->
    <profile>
        <id>production</id>
        <activation>
            <property>
                <name>profile</name>
                <value>prod</value>
            </property>
        </activation>
        <properties>
            <build.profile.id>prod</build.profile.id>
        </properties>

    </profile>

    <!-- Development Profile -->
    <profile>
        <id>development</id>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
        <properties>
            <build.profile.id>dev</build.profile.id>
        </properties>
    </profile>

    <!-- Integration Test Profile -->
    <!-- Use mvn -Dprofile=test -->
    <profile>
        <id>integration-test</id>
        <activation>
            <property>
                <name>profile</name>
                <value>test</value>
            </property>
        </activation>
        <properties>
            <!-- Used to locate the profile specific configuration file -->
            <build.profile.id>test</build.profile.id>
            <!-- Only integration tests are run. -->
            <skip.integration.tests>false</skip.integration.tests>
            <skip.unit.tests>true</skip.unit.tests>
        </properties>
    </profile>

接下来在我的 spring 上下文配置文件中:

@PropertySource("classpath:properties/app-${profile:dev}.properties")

所以这些技巧允许我使用不同的配置运行我的项目。我还有 3 个配置属性文件,在那个文件中有:

spring.profiles.active=integration-test
spring.profiles.active=prod
spring.profiles.active=dev

此配置完美运行。活动配置文件如我预期的那样发生变化,例如当我运行mvn clean install -Dprofile=test 时,我正在使用app-test.properties 文件并且我的活动配置文件是integration-test

但是这个技巧有一个问题。当有人运行 mvn install -Pintegration-test 时,活动配置文件是 dev 而不是集成测试。所以可以运行mvn install -Pintegration-test 然后设置属性配置文件来测试??

【问题讨论】:

  • 当你说 active profile 是什么时,你是指 spring profile 还是 maven profile?
  • 是的。 Spring 没有发现 ${profile} 的值,这就是选择其默认值“dev”的原因。

标签: java spring maven


【解决方案1】:

您不应该在每个环境中使用 Maven 配置文件。使用 Maven,您可以构建 jar/war/ear。不同的环境不应该导致另一个工件。因此,您应该将配置拉到此工件之外。 How to pass value to maven pom.xml at rum time from java file? 描述了很多如何解决这个问题的选项。

【讨论】:

  • “你不应该在每个环境中使用 Maven 配置文件。”,他确实应该这样做,但不是这样 :)。正如 eis 所说,区别在于 Spring 配置文件不是 Maven 配置文件。混乱由此而来。
【解决方案2】:

请尝试-P+integration-test选项

【讨论】:

    猜你喜欢
    • 2019-10-06
    • 2015-04-18
    • 2016-06-30
    • 2014-08-23
    • 1970-01-01
    • 1970-01-01
    • 2021-11-15
    • 1970-01-01
    • 2016-12-18
    相关资源
    最近更新 更多