Spring @Configuration Annotation with Example

In this article, we will discuss a very important Spring Java-based configuration annotation which is a @Configuration annotation with examples.

@Configuration Annotation Overview

Spring @Configuration annotation is part of the spring core framework. 
Spring @Configuration annotation indicates that the class has @Bean definition methods. So Spring container can process the class and generate Spring Beans to be used in the application.
Calls to @Bean methods on @Configuration classes can also be used to define inter-bean dependencies.

Importing Additional Configuration Classes

You need not put all your @Configuration into a single class. The @Import annotation can be used to import additional configuration classes. Alternatively, you can use @ComponentScan to automatically pick up all Spring components, including @Configuration classes.
 
Read more about @Import annotation on Spring @Import Annotation with Example

Refer below diagram shows an internal implementation for your reference:

@Configuration Annotation Example

The simplest possible @Configuration class would read as follows:
import org.springframework.boot.SpringApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.companyname.projectname.customer.CustomerService;
import com.companyname.projectname.order.OrderService;

@Configuration
public class Application {

     @Bean
     public CustomerService customerService() {
         return new CustomerService();
     }
 
     @Bean
     public OrderService orderService() {
         return new OrderService();
     }
} 
The AppConfig class above would be equivalent to the following Spring XML:
<beans>
        <bean id="customerService" class="com.companyname.projectname.CustomerService"/>
        <bean id="orderService" class="com.companyname.projectname.OrderService"/>
</beans>

Injecting inter-bean dependencies

When @Bean have dependencies on one another, expressing that dependency is as simple as having one bean method call another:
@Configuration
public class AppConfig {

    @Bean
    public Foo foo() {
        return new Foo(bar());
    }

    @Bean
    public Bar bar() {
        return new Bar();
    }
}
In the example above, the foo bean receives a reference to the bar via constructor injection. 

Related Spring and Spring Boot Annotations


Continue Learning with Java Guides

Want to take your programming skills to the next level? Explore my practical Udemy courses on Java, Spring Boot, Microservices, Full-Stack Development, Docker, and Generative AI. You can also follow my structured learning roadmaps to become a professional developer.

By Ramesh Fadatare - Udemy Instructor Partner

Comments