Spring Boot
@Bean
Spring Framework
Dependency Injection
Java Development

Where to put Bean in Spring Boot?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Overview of `@Bean` in Spring Boot

Spring Boot, an extension of the Spring framework, simplifies the application development process by providing a range of microservices architecture capabilities. One of the essential components of Spring Boot is dependency injection, a feature that allows the construction of objects outside your application's logic. This is achieved using annotations, with `@Bean` being one of the core annotations used to define beans in the Spring's Inversion of Control (IoC) container.

Understanding `@Bean`

In Spring Boot, a bean is an object that is managed by the IoC container. The `@Bean` annotation tells Spring that a method produces a bean that should be managed by the Spring container. The method annotated with `@Bean` will produce an instance of the desired class, which can then be injected into other beans using the `@Autowired` annotation.

Technical Explanation

The `@Bean` annotation is typically used within a `@Configuration` class. A class that is annotated with `@Configuration` indicates that it contains one or more `@Bean` methods, and Spring should process this class to generate Spring beans for the application context.

Here's a simple example:

  • Usage: This is the most common and recommended place to define beans.
  • Example:
  • Usage: While not conventional, sometimes beans are defined in classes annotated with `@Component`, `@Service`, `@Repository`, or `@Controller`.
  • Example:
  • Note: This approach is less common and could lead to less predictability. It's better to use `@Configuration` for defining beans.
  • Usage: Configuration classes can also be imported from other modules of your application.
  • Example:
  • Singleton (default): Only one instance per Spring IoC container.
  • Prototype: A new instance is created every time it is requested.
  • There's also support for other scopes like `request`, `session`, `globalSession` for web applications.
  • Custom Initialization: You can define custom initialization logic with the method containing `@Bean`.
  • Flexible and Granular Configuration: Allows more control than component scanning with `@Component`.
  • Dependency Resolution: Helps in resolving dependencies effectively by allowing Spring to manage object instances.
  • Ensure that the `@Configuration` class is picked up during component scanning, usually by enabling it in the main application class via `@SpringBootApplication`.
  • Use `@Bean` only when you want to have complete control over the instantiation of beans, otherwise prefer annotation-based configuration like `@Component`.

Course illustration
Course illustration

All Rights Reserved.