@Bean Annotation in Spring: What It Is and How It Works
@Bean is an annotation used to tell the framework to create and manage an object as a bean in its application context. It marks a method that returns an object to be registered and used by Spring for dependency injection.How It Works
Think of Spring's application context as a kitchen where all ingredients (objects) are prepared and ready to be used in recipes (your application). The @Bean annotation is like a recipe card that tells Spring how to make a specific ingredient. When Spring starts, it looks for these recipe cards and follows them to create and store the objects.
When you mark a method with @Bean, Spring runs that method once and keeps the result in its context. Later, whenever your application needs that object, Spring gives the same prepared object instead of making a new one. This helps manage resources and keeps your app organized.
Example
This example shows a simple Spring configuration class with a @Bean method that creates a String bean. Spring will manage this string and provide it wherever needed.
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class AppConfig { @Bean public String greeting() { return "Hello, Spring!"; } }
When to Use
Use @Bean when you want to create and configure objects manually inside a Spring configuration class. This is helpful when you need to integrate third-party classes or write custom setup code that Spring cannot create automatically.
For example, if you want to create a database connection, a service object, or a utility class that requires special setup, you define a @Bean method. Spring then manages these objects and injects them where needed, making your code cleaner and easier to maintain.
Key Points
- @Bean marks a method to produce a Spring-managed object.
- Spring calls the method once and stores the result as a singleton by default.
- It helps integrate objects not created by Spring automatically.
- Used inside classes annotated with
@Configuration. - Supports dependency injection and lifecycle management.
Key Takeaways
@Bean tells Spring to create and manage an object from a method.@Bean method once and reuses the object as a singleton.@Bean to configure objects that Spring cannot create automatically.@Bean methods inside @Configuration classes for proper setup.