Member-only story
Why, When, and How to Use @Bean Annotation in Spring Boot App
Learn why the @Bean
annotation is essential in Spring Boot. Discover when to use @Bean
, how it differs from @Component
, and how it helps define Spring-managed beans manually.
๐ Introduction
In Spring Boot, the @Bean
annotation is used to manually define and manage Spring beans. While Spring automatically detects components using annotations like @Component
, @Service
, and @Repository
, sometimes we need more control over bean creation.
So, when should you use @Bean
instead of @Component
? This guide will explain why, when, and how to use the @Bean
annotation effectively.
What is the @Bean Annotation?
The @Bean
annotation in Spring Boot defines a Spring-managed bean inside a configuration class.
โ It is used inside a class annotated with @Configuration
.
โ The method annotated with @Bean
returns an object that Spring registers as a bean.
โ Unlike @Component
, @Bean
gives full control over bean creation.
When to Use @Bean in Spring Boot?
You should use @Bean
in the following cases:
โ 1. When You Need to Configure a Third-Party Library
If you need to integrate a library that does not have Spring annotations, you must manually define its bean.
โ 2. When You Need to Customize Bean Creation
You may need to pass custom parameters while creating a bean, which is not possible with @Component
.
โ 3. When Using Java-Based Configuration Instead of Component Scanning
If you prefer explicit Java-based configuration, @Bean
helps define beans programmatically instead of relying on automatic scanning.
How to Use @Bean in Spring Boot?
โ Example 1: Defining a Simple Bean
@Configuration
public class AppConfig {
@Bean
public String sampleBean() {
return "Hello, Spring Boot!";
}
}