@Configuration - A look at Spring Annotations in Depth

Hello and welcome to the series of "Spring Annotations in Depth". In each article, we take an in-depth look at the most widely used annotation in Spring Framework and provide examples to make it easy to understand and use in your application.


Annotation First Release Version First Release Date
@Configuration Spring 3.0 November 2009


A Brief History before Spring 3.0


Definition: @Configuration



Example: @Configuration with Spring + Maven



Step 1:

Add the spring-context dependency in the pom.xml file.

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>6.0.10</version>
    </dependency>
</dependencies>


Step 2:

Create Java bean class(es) to be managed managed using @Configuration class.

public class Employee {
    private String empName;
    private int empId;

    public String getEmpName() {
        return empName;
    }

    public void setEmpName(String empName) {
        this.empName = empName;
    }

    public int getEmpId() {
        return empId;
    }

    public void setEmpId(int empId) {
        this.empId = empId;
    }
}


Step 3:

Create the @Configuration class to manage the Employee bean.

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AppConfig {

    @Bean
    public Employee employee() {
        Employee employee = new Employee();
        employee.setEmpId(100);
        employee.setEmpName("Sam Smith");
        return employee;
    }
}


Example: @Configuration with Spring Boot + Gradle


Step 1:

Add the spring-boot-starter dependency in build.gradle file.

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter'
}

Step 2:

Create the Bean Java Class that is to be managed using @Configuration class.

public class Employee {
    private String empName;
    private int empId;

    // Getters and setters
}

Step 3:

Create the @Configuration class with @Bean methods.

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AppConfig {

    @Bean
    public Employee employee() {
        Employee employee = new Employee();
        employee.setEmpId(100);
        employee.setEmpName("Alan Wise");
        return employee;
    }
}

Comments & Discussion

Facing issues? Have questions? Post them here! We're happy to help!