Skip to content

Instantly share code, notes, and snippets.

@LMnet
Last active August 29, 2015 14:05
Show Gist options
  • Save LMnet/be048f184b189fffd3f3 to your computer and use it in GitHub Desktop.
Save LMnet/be048f184b189fffd3f3 to your computer and use it in GitHub Desktop.
Transparently set properties in resources through gradle extra properties
//pass extra properties in resource files
processResources {
filter org.apache.tools.ant.filters.ReplaceTokens,
tokens: ExtraPropertiesToMapConverter.convert(project.getRootProject().ext.properties)
}
/**
* Convert extra properties with multilevel nesting into simple map.
* Each nesting level is separated by '.'.
*
* For example, this:
* <pre>
* ext {
* elem1 = 'val1'
* elem2 = 'val2'
* lev1 = [
* elem1: 'val1',
* elem2: 'val2',
* lev2: [
* elem1: 'val1',
* elem2: 'val2',
* ]
* ]
* }
* </pre>
* Became that:
* <pre>
* {
* elem1=val1,
* elem2=val2,
* lev1.elem1=val1,
* lev1.elem2=val2,
* lev1.lev2.elem1=val1,
* lev1.lev2.elem2=val2,
* }
* </pre>
* @param properties
* @return
*/
class ExtraPropertiesToMapConverter {
/**
* Facade method for converting
*
* @param extraProperties
* @return
*/
public static HashMap<String, String> convert(Map extraProperties) {
def map = new HashMap<String, String>();
converter(extraProperties, map, '');
return map;
}
/**
* Main convert method
* For each nesting level run recursively with prefix adding.
*
* @param properties Source map
* @param map Result map
* @param prefix Prefix, added to key
*/
private static void converter(Map properties, Map map, String prefix) {
properties.each {key, value ->
value instanceof Map ?
converter(value, map, prefix + key + '.') :
map.put(prefix + key, value);
}
}
}
ext {
db = [
host: 'localhost',
schemaName: 'schemaName',
username: 'root',
password: '123',
]
}
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://@db.host@/@db.schemaName@"/>
<property name="username" value="@db.username@"/>
<property name="password" value="@db.password@"/>
</bean>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment