@SpringBootConfiguration annotation in Spring Boot is a class-level annotation which indicates that this class provides the application configuration.
Generally, the class with the main() method is best-suited for this annotation.
We usually use @SpringBootApplication annotation which automatically inherits the @SpringBootConfiguration annotation.
When we mark a class with @SpringBootConfiguration, it means that the class provides @Bean definition methods. The Spring container processes the configuration class to instantiate and configure beans for our application.
Let’s see an example usage of this annotation:
@SpringBootConfiguration public class DemoApp { public static void main(String[] args) { SpringApplication.run(DemoApp.class, args); } @Bean public Course course() { return new Course(); } @Bean public Student student() { return new Student(); } }
As per the Spring documentation, @SpringBootConfiguration is just an alternative to the Spring standard @Configuration annotation. The only difference between the two is that the @SpringBootConfiguration allows the configuration to be found automatically.
This is specifically useful when writing tests.
As we discussed earlier, the @SpringBootApplication annotation includes @SpringBootConfiguration annotation:
@Target(value=TYPE) @Retention(value=RUNTIME) @Documented @Inherited @SpringBootConfiguration @EnableAutoConfiguration @ComponentScan(excludeFilters={@ComponentScan.Filter(type =CUSTOM,classes=TypeExcludeFilter.class)}) public @interface SpringBootApplication
Please note that it is recommended to only use exactly one @SpringBootConfiguration or @SpringBootApplication annotation in our application.
While writing test cases for our Spring Boot application, one of the common exceptions we encounter is:
Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test java.lang.IllegalStateException
Make sure that your test classes are either in the same package as your class marked with @SpringBootApplication or at least lower in the package hierarchy:
sample-app +--pom.xml +--src +--main +--com +--programmergirl +--Application.java +--test +--com +--programmergirl +--test +--SampleJpaTest.java
In this mini-tutorial, we talked about the @SpringBootConfiguration annotation. We also saw that @SpringBootApplication includes the definition for the @SpringBootConfiguration.
And, we compared the standard Spring @Configuration with the @SpringBootConfiguration.
We have another article onĀ Spring core Annotations that can help you learn some common annotations used in a Spring application. Please feel free to explore if you feel so.