I would like to get a property value from Gradle.properties in Java class. In Java, the value should be replaced at build time, and in the .jar(.class) file the value will come but not in a .java file. So that we can change the value directly in gradle.properties and no need to change the code. Is it possible to achieve?
Asked
Active
Viewed 4,277 times
1 Answers
1
It would be easier to answer if you told your specific use case. Also it would help to know your application, for example is it a Spring (Boot) app? In that case it would probably make more sense to use Spring Profiles for that.
Anyway, here is a possible solution:
Create a properties file and put it in your resources folder. Define a placeholder, that gradle can replace. For example file "myapp.properties"
greetingText=@greeting@
Add the token (the text between the '@'s) to your gradle.properties:
greeting=Hello world!
Make the build.gradle replace the token with the value from gradle.properties by configuring the processResources task:
processResources { inputs.file file('gradle.properties') filter( ReplaceTokens, tokens: [ greeting: project.ext.greeting ] )
}
At runtime load the value from the properties file:
public String getGreeting() throws IOException { try ( InputStream inputStream = Thread.currentThread().getContextClassLoader().getResource("myapp.properties").openStream(); ) { Properties appProps = new Properties(); appProps.load(inputStream); return appProps.getProperty("greetingText"); } }

eekboom
- 5,551
- 1
- 30
- 39
-
Thanks for the answer. But is there any way to update the value directly from gradle.properties to java class? – Sumanta Biswas Mar 20 '19 at 17:13
-
Well, you _could_ either preprocess the Java source code or after compilation manipulate the byte code with a tool like ByteBuddy, cglib, or javassist to manipulate the byte code of the compiled class, but that seems to be a big hack. – eekboom Mar 21 '19 at 15:23