spring maven profile - 根据编译配置文件设置属性文件

时间:2018-02-05 09:13:21

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

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

  • 个人资料名称:dev
  • 个人资料名称:test
  • 个人资料名称:production

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

  • 开发/ file.properties
  • 测试/ file.properties
  • 生产/ file.properties

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

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

之后我会在Spring类中设置类似这样的东西:

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

}

我该怎么办?

1 个答案:

答案 0 :(得分:1)

请参阅 Apache Maven Resources Plugin / FilteringMaven: The Complete Reference - 9.3. Resource Filtering。 (过滤是一个坏名字,恕我直言,因为过滤器通常过滤 out ,而我们在这里执行字符串插值。但这就是它的方式。)

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

声明默认属性(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 ...