Custom Spring Boot Configuration with Annotation

Shahbaz Khan
2 min readJun 26, 2021

Overview

Usually, when working on large projects with multiple teams we create some common libraries. These libraries or jar files are then added to multiple projects as a dependency.

We will see how to create a Spring Configuration class in a common library and then enable it using a custom annotation in another Spring Project

Step 1

Create a Configuration class

@Configuration
public class MyCustomConfiguration {
public MyBean myBean(){
return new MyBean()
}
}

Step 2

Create a class that implements spring’s ImportSelector interface and then and MyCustomConfiguration class as shown below

import org.springframework.context.annotation.ImportSelector;
import org.springframework.core.type.AnnotationMetadata;
public class MyCustomConfigImporter implements ImportSelector {@Override
public String[] selectImports(AnnotationMetadata metadata) {
return new String[]{
"your.package.name.MyCustomConfiguration"
};
}
}

As shown above we can add multiple configuration classes using the fully qualified name and pass it as a string array.

Step 3

Create a custom Annotation and bind it with MyCustomConfigImporter

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Import({MyCustomConfigImporter.class})
public @interface EnableMyCustomConfiguration {

}

We have created a custom annotation EnableMyCustomConfiguration and then we imported our MyCustomConfigImporter class in the annotation.

The line below ensures that our custom annotation when used will import all the configuration added in step 2

@Import({MyCustomConfigImporter.class})

Step 4

Use the custom annotation in the application

@SpringBootApplication
@EnableMyCustomConfiguration
public class Application {

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

}
}

We can now use the @EnableMyCustomConfiguration annotation at runtime spring will import all the configuration class mention in the MyCustomConfigImporter and create beans accordingly

I would like to hear your thoughts, questions, or suggestions :)

--

--