Custom Auto-Configuration in SpringBoot
18 Feb 2020 1 min read java springboot spring auto-configurationIntroduction
The goal of this blog is to understand the autoconfiguration provided by SpringBoot. I’ll be creating a logging library for demo purpose and that will include Auto-Configuration class to create all required beans for that library.
Technologies used
- Java 11
- Spring Boot 2.2.4
- Gradle 6.0.1
Project Structure
I’m using a Gradle multi-module project. The module logging-library
will be a shared library that will be used in the service
module.
Create config classes
Now It’s time to create required config classes. I’ve created a config class called LoggingAutoConfiguration
and marked as @Configuration
and created one conditional bean.
@Configuration
public class LoggingAutoConfiguration {
// We can define beans here
@ConditionalOnMissingBean(Logger.class)
@Bean
public Logger getLogger() {
return new ConsoleLogger();
}
}
As of now this class is just a normal spring configuration and to make it auto-configuration class we need to follow 2 steps:
Step 1: Create spring.factories file
Create a file inlogging-library
with name spring.factories
under resources\META-INF\
directory.
Step 2: Register the auto-config class
Now add your configuration class into the spring.factories
.
org.springframework.boot.autoconfigure.EnableAutoConfiguration=tutorials.logging.LoggingAutoConfiguration
That’s it!!!
Now we can inject the module in service
and we don’t need to specify any package to scan from logging-library
our auto-configuration class will take care of that.
You can find the running code here