What is a Bean in Spring, and how do you define it?
A Bean is simply a Java object that is instantiated, configured, and managed by the Spring IoC (Inversion of Control) container. It’s the backbone of a Spring application.
How to Define a Bean
- Using Annotations:
- @Component: Marks a class as a Spring-managed bean.
- Specialized versions: @Service, @Repository, @Controller.
@Component class MyBean { }
- Using @Bean in a Configuration Class:
- Used for more control or when external libraries are involved.
@Configuration class AppConfig { @Bean public MyBean myBean() { return new MyBean(); } }
-
Using XML Configuration (Less common now):
<bean id="myBean" class="com.example.MyBean"/>
Key Point
Spring automatically manages the lifecycle and dependencies of beans, ensuring loose coupling and easier configuration.