Sumanta Biswas
Sumanta Biswas

Reputation: 13

How to get value from gradle.properties in .class file at the time of build

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?

Upvotes: 1

Views: 4637

Answers (1)

eekboom
eekboom

Reputation: 5822

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");
        }
    }
    

Upvotes: 1

Related Questions