StackTips

Spring Bean Configuration using @Configuration and @Bean Annotations

nilan avtar

Written by

Nilanchala,  4 min read,  3.12K views, updated on Sept. 17, 2023

In our previous tutorial, we have declared and configured Spring bean classes using XML configuration file. If you want to reduce the number of XML configuration files, you can do so by configuring the Spring POJO for the Spring IoC container using @Configuration and @Bean annotation.

@Configuration & @Bean Annotations

Annotating a class with the @Configuration indicates that the class can be used by the Spring IoC container as a source of bean definitions.

The @Bean annotation tells Spring that a method annotated with @Bean will return an object that should be registered as a bean in the Spring application context.

Let us examine how to use the @Configuration and @Bean annotation to configure the following bean class.

public class Toy {
    private String name;
    private double price;

    public Toy() { }
    public Toy(String name, double price) {
        this.name = name;
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }
}

The above bean class can be configured using the following XML configuration.

The following code snippet shows the simplest form of bean declaration using @Configuration and @Bean annotation.

@Configuration
public class MyBeanConfig {

    @Bean
    public Toy crayonToy() {
        return new Toy();
    }
}

Here the method name annotated with @Bean works as bean ID and it creates and returns actual bean instance. Your configuration class can have declaration for more than one @Bean.

Once your configuration classes are defined, you can load & provide them to Spring container using AnnotationConfigApplicationContext class.

AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.register(MyBeanConfig.class);
context.refresh();

Crayon myService = context.getBean(Crayon.class);