michele
michele

Reputation: 26598

spring maven profile - set properties file based on compilation profile

I would create some compilation profiles like these:

In src/main/resources I have 3 folders:

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?

Upvotes: 2

Views: 2906

Answers (1)

Gerold Broser
Gerold Broser

Reputation: 14762

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

Upvotes: 2

Related Questions