Spring application.properties configuration

The first step for most Spring Boot developers is to use application.properties. The Spring Initializr even puts an empty application.properties in the src/main/resources/application.properties. folder when you generate a new project there! Super convenient. You do create your projects on the Spring Initializr, don’t ya’? You could use appication.properties or applicatin.yml. I don’t particularly love .yml files, but you can use it if that’s more your taste.

Spring Boot automatically loads the application.properties whenever it starts up. You can dereference values from the property file in your java code through the environment. Put a property in the application.properties file, like this.

message-from-application-properties=Hello from application.properties
Now, let’s edit the code to read in that value.

package com.example.configuration;

import lombok.extern.log4j.Log4j2;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;

@Log4j2
@SpringBootApplication
public class ConfigurationApplication {

    public static void main(String[] args) {
        SpringApplication.run(ConfigurationApplication.class, args);
    }

    @Bean
    ApplicationRunner applicationRunner(Environment environment) {
        return args -> {
            log.info("message from application.properties " + environment.getProperty("message-from-application-properties"));
        };
    }
}
Run this, and you’ll see the value form the configuration property file in the output of the log. If you want to change which file SPring Boot rads by default, you can do that too. It’s a chicken and egg problem, though - you need to specify a property that Spring Boot will use to figure out where to load all the properties. So you need to specify this outside of the application.properties file. You can use a program argument or an environment variable to fill the spring.config.name property.

export SPRING_CONFIG_NAME=foo
Re-run the application now with that environment variable in scope, and it’ll fail because it’ll try to load foo.properties, not application.properties.

Incidentally, you could also run the application with the configuration that lives outside the application, adjacent to the jar, like this. If you run the application like this, the values in the external applicatin.properties will override the values inside the .jar.

.
├── application.properties
└── configuration-0.0.1-SNAPSHOT.jar

0 directories, 2 files

Comments

Popular posts from this blog

Today Walkin 14th-Sept

Hibernate Search - Elasticsearch with JSON manipulation

Spring Elasticsearch Operations