DEV Community

Jitendra Singh Bisht
Jitendra Singh Bisht

Posted on • Edited on

4

Custom Auto-Configuration in SpringBoot

The blog is originally published on my blog jsblogs.github.io


Introduction

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

Alt Text

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.

Alt Text

You can find the running code here

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Cloudinary image

Zoom pan, gen fill, restore, overlay, upscale, crop, resize...

Chain advanced transformations through a set of image and video APIs while optimizing assets by 90%.

Explore

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay