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

  1. Using Annotations:
    • @Component: Marks a class as a Spring-managed bean.
    • Specialized versions: @Service, @Repository, @Controller.
    @Component
    class MyBean { }
    
  2. 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();
        }
    }
    
  3. 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.