Spring Boot Properties
Aliasing and system environment overrides
September 15, 2018Spring properties env and aliasing
This is a short article about spring properties and how you can alias them and override them via environment variables.
First things first.
- Create a bean to display the properties
- In here I am using Project Lombok to generate code such as slf4j loggers.
- Make sure the class is @Component or @Service
- @Autowire Environment and ServerProperties
- Create Post Construct method - at least for this purpose, we'll use this method to print variables.
- In this method you are attempting to read a property from the environment and your aliased property.
package com.scrap;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
@Slf4j
@Component
public class ShowProperties {
@Autowired
private Environment environment;
@Autowired
private ServerProperties serverProperties;
@PostConstruct
public void postsConfigure() {
log.info(environment.getProperty("USERNAME"));
log.info("compression {}", serverProperties.getCompression().getEnabled());
}
}
Aliasing the property
In application.properties add the variable you'd like to access; in this case we are using server.compression.enabled; although the variable won't be used for anything other than printing.
Alias the name using the following syntax ${aliasName: defaultValue}
server.compression.enabled=${compression: false}
Export the variable via Environment Variables
export COMPRESSION=true
export USERNAME=Bob
Run Spring
Via Maven
mvn spring-boot:run
Via Java
java -jar YourProject.jar
Output
2018-09-15 13:56:43.822 INFO 89653 --- [main] com.scrap.ShowProperties : compression true
2018-09-15 13:56:43.822 INFO 89653 --- [main] com.scrap.ShowProperties : Bob
...Long environment variables are still resolved
If you'd like to continue using the long name. You can.
export SERVER_COMPRESSION_ENABLED=true
/.
() -> loger.info("/.Springzen");
Architect
Posted in: javapropertiesspring
