Tutorials Spring Spring Bean Configuration using @Configuration and @Bean Annotations

Spring Bean Configuration using @Configuration and @Bean Annotations

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);
Total
0
Shares
guest
0 Comments
Inline Feedbacks
View all comments
Previous Post

Create and Manage POJOs with Spring IoC Container

Next Post

Spring Bean Scope Using XML Configuration and @Scope Annotation

Related Posts
By clicking “Allow All”, you agree to the storing of cookies on your device to enhance site navigation, analyze site usage, and assist in our marketing efforts. Cookie Notice
Allow All
0
Would love your thoughts, please comment.x
()
x