Tutorial

Spring @Bean Annotation

Published on August 3, 2022
author

Pankaj

Spring @Bean Annotation

Spring @Bean Annotation is applied on a method to specify that it returns a bean to be managed by Spring context. Spring Bean annotation is usually declared in Configuration classes methods. In this case, bean methods may reference other @Bean methods in the same class by calling them directly.

Spring @Bean Example

Let’s say we have a simple class as below.

package com.journaldev.spring;

public class MyDAOBean {

	@Override
	public String toString() {
		return "MyDAOBean"+this.hashCode();
	}
}

Here is a Configuration class where we have defined a @Bean method for MyDAOBean class.

package com.journaldev.spring;

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

@Configuration
public class MyAppConfiguration {

	@Bean
	public MyDAOBean getMyDAOBean() {
		return new MyDAOBean();
	}
}

We can get MyDAOBean bean from Spring context using below code snippet.

AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.scan("com.journaldev.spring");
context.refresh();
		
//Getting Bean by Class
MyDAOBean myDAOBean = context.getBean(MyDAOBean.class);

Spring Bean Name

We can specify the @Bean name and use it to get them from spring context. Let’s say we have MyFileSystemBean class defined as:

package com.journaldev.spring;

public class MyFileSystemBean {

	@Override
	public String toString() {
		return "MyFileSystemBean"+this.hashCode();
	}
	
	public void init() {
		System.out.println("init method called");
	}
	
	public void destroy() {
		System.out.println("destroy method called");
	}
}

Now define a @Bean method in the configuration class:

@Bean(name= {"getMyFileSystemBean","MyFileSystemBean"})
public MyFileSystemBean getMyFileSystemBean() {
	return new MyFileSystemBean();
}

We can get this bean from context by using the bean name.

MyFileSystemBean myFileSystemBean = (MyFileSystemBean) context.getBean("getMyFileSystemBean");

MyFileSystemBean myFileSystemBean1 = (MyFileSystemBean) context.getBean("MyFileSystemBean");

Spring @Bean initMethod and destroyMethod

We can also specify spring bean init method and destroy method. These methods are called when spring bean is being created and when the context is being closed respectively.

@Bean(name= {"getMyFileSystemBean","MyFileSystemBean"}, initMethod="init", destroyMethod="destroy")
public MyFileSystemBean getMyFileSystemBean() {
	return new MyFileSystemBean();
}

You will notice that “init” method is being called when we invoke the context refresh method and “destroy” method is called when we invoke context close method.

Summary

Spring @Bean annotation is widely used in annotation-driven spring applications.

You can download the complete spring project from our GitHub Repository.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Pankaj

author

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
June 20, 2020

Is creating a AnnotationConfigApplicationContext the only way to get the bean Which inject with @Bean Annotatiion?

- xunyan

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    February 23, 2020

    Thanks, nice post

    - Binh Thanh Nguyen

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      December 2, 2018

      Thanks for the article pankaj. does context.getBean(“MyFileSystemBean”) call create new object every time? or is it singleton?

      - Hemachandra

        Try DigitalOcean for free

        Click below to sign up and get $200 of credit to try our products over 60 days!

        Sign up

        Join the Tech Talk
        Success! Thank you! Please check your email for further details.

        Please complete your information!

        Become a contributor for community

        Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

        DigitalOcean Documentation

        Full documentation for every DigitalOcean product.

        Resources for startups and SMBs

        The Wave has everything you need to know about building a business, from raising funding to marketing your product.

        Get our newsletter

        Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

        New accounts only. By submitting your email you agree to our Privacy Policy

        The developer cloud

        Scale up as you grow — whether you're running one virtual machine or ten thousand.

        Get started for free

        Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

        *This promotional offer applies to new accounts only.