spring maven profile - set properties file based on compilation profile

随声附和 提交于 2021-02-10 12:14:02

问题


I would create some compilation profiles like these:

  • profile name: dev
  • profile name: test
  • profile name: production

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

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

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

}

How can I do?


回答1:


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.)

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

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>
  ...

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>
  ...

Use in your code just:

@PropertySource("file:file.properties")

Activate the profiles with:

mvn ... -P test ...

or

mvn ... -P prod ...


来源:https://stackoverflow.com/questions/48619079/spring-maven-profile-set-properties-file-based-on-compilation-profile

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!