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

前端 未结 2 1663
清酒与你
清酒与你 2021-01-23 19:03
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

相关标签:
2条回答
  • 2021-01-23 19:26

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

    0 讨论(0)
  • 2021-01-23 19:38

    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>
    
    0 讨论(0)
提交回复
热议问题