【问题标题】:spring maven profile - set properties file based on compilation profilespring maven profile - 根据编译配置文件设置属性文件
【发布时间】:2018-07-15 02:28:31
【问题描述】:

我会创建一些像这样的编译配置文件:

  • 个人资料名称:开发人员
  • 个人资料名称:test
  • 个人资料名称:生产

在 src/main/resources 我有 3 个文件夹:

  • dev/file.properties
  • test/file.properties
  • 生产/file.properties

每个文件都包含该属性的不同值:

- my.prop.one
- my.prop.two
- my.prop.three

之后我会在 Spring 类中设置如下内容:

@Configuration
@PropertySource("file:${profile_name}/file.properties")
public class MyConfig{

}

我该怎么办?

【问题讨论】:

  • 在生产代码中使用依赖于您的构建环境的变量不是一个干净的解决方案。 dev 测试和test 测试有什么区别?如果您可以将其减少到test 和production,您可以在/src/main/resources 中放置一个file.properties,在/src/test/resources 中放置一个,Maven 将自动处理它们的打包。
  • 不,我有 3 个环境。我该怎么办=
  • 这三个file.properties只是在相同的配置行中配置值不同还是它们也包含不同的配置行?
  • 它们只包含不同的属性值。
  • 很好。这使它更容易。看我的回答。

标签: maven maven-plugin spring-profiles maven-profiles spring-properties


【解决方案1】:

见 Apache Maven Resources Plugin / Filtering 和Maven: The Complete Reference - 9.3. Resource Filtering。 (Filtering 是一个不好的名字,恕我直言,因为过滤器通常会过滤 out 的东西,而我们在这里执行 字符串插值。但事实就是这样.)

在src/main/resources 中创建一个 file.properties,其中包含应根据您的环境更改的值的${...} 变量。

声明默认属性(dev 的那些)并在您的 POM 中激活资源过滤:

<project>
  ...
  <properties>
    <!-- dev environment properties, 
         for test and prod environment properties see <profiles> below -->
    <name>dev-value</name>
    ...
  </properties>

  <build>
    <resources>
      <resource>
        <directory>src/main/resources</directory>
        <filtering>true</filtering>
      </resource>
    </resources>
  </build>
  ...

在您的 POM 中声明两个具有相应属性的配置文件:

  ...  
  <profiles>
    <profile>
      <id>test</id>
      <properties>
        <name>test-value</name>
        ...
      </properties>
    </profile>

    <profile>
      <id>prod</id>
      <properties>
        <name>prod-value</name>
        ...
      </properties>
    </profile>

  </profiles>
  ...

仅在您的代码中使用:

@PropertySource("file:file.properties")

激活配置文件:

mvn ... -P test ...

或

mvn ... -P prod ...

【讨论】:

  • 有了这个解决方案,属性值是硬编码在 pom 中的?我不确定我是否理解。
  • @michele 你看过我提供的第二个链接中的例子了吗?这基本上准确地描述了您正在寻找的内容:“如果您需要在开发中使用不同的 [x] 并在生产中使用不同的 [x]。”并且它以与我相同的方式完成在这里为您的需求描述。
  • @michele“硬编码”在这里是错误的词。这些值必须在最后的某个地方定义。现在想想有什么更好、更简洁的解决方案:拥有 三个 文件,它们的配置值不同(记住 DRY),其中 all 包含“硬编码”值 和 生产代码中的构建时间依赖性,我们尚不知道如何解决或只有一个文件使用它们所属的值动态更新:构建配置(您的标题问题包含“基于编译配置文件”)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-03
  • 2020-06-03
  • 2013-09-24
  • 2012-05-27
  • 2010-12-03
  • 1970-01-01
相关资源
最近更新 更多