You can write an implementation of the interface EnvironmentPostProcessor
to customize the Environment
of a Spring Boot application.
For example you can read an external configuration file and add its properties to the Environment
.
If you want to add some logging statement to the class then you need to make sure you pass a DeferredLogFactory
to the constructor of the class.
From this factory you can use the getLogger
method to get a Log
instance.
This is needed, because the implementation of the interface EnvironmentPostProcessor
is created before the logging system is initialized.
By using the Log
instances created from DeferredLogFactory
Spring Boot will make sure the log messages are written when the logging system is initialized.
In the following example you can see how to use the DeferredLogFactory
:
package mrhaki.sample; import org.apache.commons.logging.Log; import org.springframework.boot.SpringApplication; import org.springframework.boot.env.EnvironmentPostProcessor; import org.springframework.boot.logging.DeferredLogFactory; import org.springframework.core.annotation.Order; import org.springframework.core.env.ConfigurableEnvironment; /** * Sample implementation for {@link EnvironmentPostProcessor}. */ @Order public class SampleEnvironmentPostProcessor implements EnvironmentPostProcessor { /** * Log instance to log messages after the logging system is initialized. */ private final Log log; /** * Create instance. * * @param logFactory Use logFactory to create logger that will output if the logging system is * initialized. */ public SampleEnvironmentPostProcessor(DeferredLogFactory logFactory) { log = logFactory.getLog(SampleEnvironmentPostProcessor.class); } @Override public void postProcessEnvironment( ConfigurableEnvironment environment, SpringApplication application) { if (log.isInfoEnabled()) { // This log message will only be written once the logging system is initialized // and the log level is INFO or higher. log.info("Sample environment post processor started"); } } }
The support for DeferredLogFactory
is added in Spring Boot 2.4.
Written with Spring Boot 3.4.2.