How to specify Spring propertyPlaceHolderConfig va

2019-06-11 15:49发布

问题:

I am migrating existing Maven build to gralde and facing this issue. In Maven pom.xml ,spring propertyplaceholderConfig values are specified in Maven profiles. Maven build specifies three types of profiles dev,test and prod

I want to achieve the same thing in gradle build but till now not able to figure out how to do it in gradle

Thanks, Manoj

回答1:

I think there are different options how you can model your existing mvn profiles with gradle. I'll give you one example here:

given you have a property file that looks like that:

property1=$prop1 //prop1 and prop2 are placeholder for your environment specific values
property2=$prop2

Now you can model your profiles in your build.gradle file:

def profileProperties = [
    test:[prop1:"testValue1", prop2:"testValue2"],
    dev:[prop1:"devValue1", prop2:"devValue2"],
    prod:[prop1:"prodValue1", prop2:"prodValue2"]
]

This is just a ordinary nested map defined in groovy.

By passing a commandline option 'profile' to your gradle call

gradle clean build -Pprofile=dev

you can pass to your gradle project what environment you're currently in. In your build script you can differentiate this by adding the following to your build file:

def usedProfile = project.getProperty("profile")

processResources{
     expand(profileProperties[usedProfile])
}

This takes your defined profileAttribute and reads the according map of environment properties. this environment properties are passed as a map to the expand filter method, that is part of the gradle API. have a look at http://gradle.org/docs/current/dsl/org.gradle.api.tasks.Copy.html#org.gradle.api.tasks.Copy:expand(java.util.Map) for details about the expand method.

The whole build.gradle file for a simple java project would now look like this:

apply plugin:'java'

def profileProperties = [
    test:[prop1:"testValue1", prop2:"testValue2"],
    dev:[prop1:"devValue1", prop2:"devValue2"],
    prod:[prop1:"prodValue1", prop2:"prodValue2"]
]


def usedProfile = project.getProperty("profile")
processResources{
    expand(profileProperties[usedProfile])
}

This is just a draft, of course you can use all groovy goodness here to add a bit more logic here, like having a default profile, etc.

hope that helps,

regards, René



标签: maven gradle