Understanding the @Bean Annotation in Spring and When to Use It

Alexander Obregon
3 min readAug 5, 2023

--

Image Source

Introduction

In Java-based application development, Spring Framework is an undeniable game-changer. Its functionality and capabilities are powered by several key annotations, one of which is the @Bean annotation. The goal of this article is to explain the @Bean annotation in Spring, help you understand its functionality, and demonstrate when and how to use it effectively.

What is the @Bean annotation?

The @Bean annotation is a method-level annotation in the Spring Framework. Part of the Spring Framework’s core container, this annotation plays a pivotal role in enabling Dependency Injection (DI) and Inversion of Control (IoC). It’s used to explicitly declare a single bean, rather than letting Spring do it automatically. The bean returned by the annotated method is registered as a bean in the Spring Application Context.

Now, you may wonder what a ‘bean’ is in the context of the Spring Framework. Simply put, a bean is an object that is instantiated, assembled, and managed by the Spring IoC container. It’s the basic building block of any Spring application.

Example of @Bean Annotation:

@Configuration
public class AppConfig {

@Bean
public MyBeanClass myBean() {
return new MyBeanClass();
}
}

In this example, the method myBean() is annotated with @Bean, which indicates that the returned object of MyBeanClass should be registered as a bean in the Spring Application Context.

When should you use @Bean?

You should use @Bean when you want to control the instantiation of a class directly. There are several scenarios where this is particularly useful:

  1. Third-party classes: If you want to instantiate a class from a third-party library, you may not be able to annotate the class directly with Spring’s @Component (or its specializations @Service, @Repository, @Controller). In this case, you can use a @Bean method in a @Configuration class.
  2. Conditional bean creation: You may want to create a bean conditionally — only under certain circumstances. This is easily done with a @Bean method.
  3. Multiple beans of the same type: If you want to create more than one bean of the same type, @Bean methods are the way to go.
  4. Creating beans with parameters: If your bean requires some parameters for its construction, you can pass them to the @Bean annotated method, and Spring will autowire them for you.

Now, let’s dive into examples illustrating the above scenarios.

Third-party classes

Suppose we have a third-party class ThirdPartyClass we can't modify directly. We can still control its instantiation using @Bean.

@Configuration
public class AppConfig {

@Bean
public ThirdPartyClass thirdPartyClass() {
return new ThirdPartyClass();
}
}

Conditional bean creation

Consider the following code snippet. We have two beans — devDataSource and prodDataSource. Based on the profile active in your Spring Application, you can conditionally load one of these.

@Configuration
public class AppConfig {

@Bean
@Profile("dev")
public DataSource devDataSource() {
return new DevDataSource();
}

@Bean
@Profile("prod")
public DataSource prodDataSource() {
return new ProdDataSource();
}
}

Multiple beans of the same type:

If you need multiple beans of the same type, you can create them using @Bean and differentiate them using names.

@Configuration
public class AppConfig {

@Bean
public MyBeanClass myBeanOne() {
return new MyBeanClass("Bean One");
}

@Bean
public MyBeanClass myBeanTwo() {
return new MyBeanClass("Bean Two");
}
}

Creating beans with parameters

If a bean requires certain parameters for its construction, you can pass them to the @Bean annotated method.

@Configuration
public class AppConfig {

@Value("${mybean.value}")
private String myBeanValue;

@Bean
public MyBeanClass myBean() {
return new MyBeanClass(myBeanValue);
}
}

In this code snippet, we are injecting a property value into our bean at the time of creation.

Conclusion

The @Bean annotation is an indispensable tool in your Spring toolkit, enabling fine-grained control over bean creation, registration, and configuration in your Spring application. By understanding and correctly using the @Bean annotation, you can fully exploit the power of the Spring Framework, making your Java-based application development smoother and more efficient.

  1. Spring Framework Documentation
  2. Baeldung — Spring Core Annotations
Spring Boot icon by Icons8

--

--

Alexander Obregon

Software Engineer, fervent coder & writer. Devoted to learning & assisting others. Connect on LinkedIn: https://www.linkedin.com/in/alexander-obregon-97849b229/