Bala
Bala

Reputation: 4547

How can I use maven profile Id value in spring bean files?

mvn -P dev

If I build my project using profile dev, then I want to use dev.properties in my spring bean like below. Is it possible ? If so , how could I get profile name ?

<bean id="xyz" class="abc.xyz">
    <property name="propertyFile" value="${maven_profile_id}.properties" />
</bean>

Thanks in advance.

Upvotes: 1

Views: 3360

Answers (2)

Jonathan
Jonathan

Reputation: 20375

You can use Maven profiles to add a 'profile' property to the build:

<profiles>
    <profile>
        <id>dev</id>
        <properties>
            <profile>dev</profile>
        </properties>
    </profile>
</profiles>

Then pass the value into your application using a system property, here's an example with surefire:

<plugin>
    <artifactId>maven-surefire-plugin</artifactId>
    <configuration>
        <systemPropertyVariables>
            <profile>${profile}</profile>
        </systemPropertyVariables>
    </configuration>
</plugin>

Finally this can be referenced in you application:

<bean id="xyz" class="abc.xyz">
    <property name="propertyFile" value="${profile}.properties" />
</bean>

Alternatively, if you are using Spring 3.1 or later you might find the XML profile feature meets your needs (although it may be overkill).

Upvotes: 1

Wilhelm Kleu
Wilhelm Kleu

Reputation: 11047

Create a properties file that will be populated using Maven's resource filtering that specifies the profile you are using at build time.

build.properties

activatedProfile=${profileId}

pom.xml (You don't need to filter the complete directory, customise as required)

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

Add a profileId (or whatever you want to call it) property under each different profile:

 <profile>
     <id>dev</id>
     <properties>
        <profileId>dev</profileId>
     </properties>
 </profile>
 <profile>
     <id>qa</id>
     <properties>
        <profileId>qa</profileId>
     </properties>
 </profile>

You can then use ${activatedProfile}.properties as value for a bean

<bean id="xyz" class="abc.xyz">
    <property name="propertyFile" value="${activatedProfile}.properties" />
</bean>

Upvotes: 0

Related Questions