spring maven 配置文件 - 根据编译配置文件设置属性文件 [英] spring maven profile - set properties file based on compilation profile

查看:117
本文介绍了spring maven 配置文件 - 根据编译配置文件设置属性文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would create some compilation profiles like these:

  • 个人资料名称:dev
  • 个人资料名称:测试
  • 个人资料名称:生产

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

In src/main/resources I have 3 folders:

  • dev/file.properties
  • test/file.properties
  • production/file.properties

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

Each file contains different values for this properties:

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

在那之后,我会在 Spring 类中设置如下:

After that I would set in Spring classes something like these:

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

}

我该怎么办?

推荐答案

参见 Apache Maven 资源插件/过滤Maven:完整参考 - 9.3.资源过滤.(过滤是个坏名字,恕我直言,因为过滤器通常会过滤的东西,而我们在这里执行字符串插值.但这就是它的方式.)

See Apache Maven Resources Plugin / Filtering and Maven: The Complete Reference - 9.3. Resource Filtering. (Filtering is a bad name, IMHO, since a filter usually filters something out, while we perform string interpolation here. But that's how it is.)

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

Create one file.properties in src/main/resources that contains ${...} variables for the values that should change according to your environment.

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

Declare default properties (those for dev) and activate resource filtering in your 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 中声明两个具有相应属性的配置文件:

Declare two profiles with the according properties in your 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")

使用以下方法激活配置文件:

Activate the profiles with:

mvn ... -P test ...

mvn ... -P prod ...

这篇关于spring maven 配置文件 - 根据编译配置文件设置属性文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆