Beans & Autowiring

What is a Spring Bean?

In the Spring Framework, a Spring Bean is a core concept that refers to an object managed by the Spring IoC (Inversion of Control) container. Essentially, a Spring Bean is a Java object that is instantiated, configured, and managed by the Spring container.


Defining a Spring Bean

Spring beans can be defined in several ways:
Example 1: XML-Based Bean Configuration
Traditionally, beans were defined in an XML file. A typical bean configuration in XML looks like this:


    <bean id="myBean" class="com.example.MyClass">
        <property name="property1" value="value1"/>
    </bean>
                    

Example 2: Annotation-Based Configuration
In modern Spring applications, beans are more commonly defined using annotations. By using the @Component annotation on a class, you can let Spring know that this class is a bean:

    @Component
    public class MyBean {
        // Your code here
    }
            

Example 3: Java-based Configuration
You can also define beans using Java-based configuration with the @Configuration and @Bean annotations:


    @Configuration
    public class MyConfig {
    
        @Bean
        public MyBean myBean() {
            return new MyBean();
        }
    }    
                


Bean Scope

Beans in Spring have different scopes, which define how and when the Spring container creates and manages bean instances.


Bean Lifecycle

The Spring IoC container is responsible for managing the full lifecycle of a Spring Bean. The lifecycle of a bean includes:

  1. Instantiation: The bean is created.
  2. Dependency Injection: Dependencies (other beans) are injected into the bean.
  3. Initialization: Any custom initialization logic (if needed) is executed.
  4. Usage: The bean is used in the application.
  5. Destruction: If applicable, the bean is destroyed, and any custom cleanup logic is executed.


How to Access Spring Beans Using ApplicationContext

ApplicationContext is the central interface for accessing Spring beans and managing the lifecycle of beans in a Spring application. It is an advanced container that provides:

There are several implementations of ApplicationContext, such as:


Example Using AnnotationConfigApplicationContext

    import org.springframework.context.ApplicationContext;
    import org.springframework.context.annotation.AnnotationConfigApplicationContext;

    public class MainApp {
        public static void main(String[] args) {
            // Create application context using Java configuration
            ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);

            // Accessing bean by type
            MyService myService = context.getBean(MyService.class);
            myService.performTask();

            // Accessing bean by name
            MyBean myBean = (MyBean) context.getBean("myBean");
            myBean.doSomething();
        }
    }
            


Example of Registering Beans Dynamically

        import org.springframework.context.annotation.AnnotationConfigApplicationContext;

        public class DynamicBeanApp {
            public static void main(String[] args) {
                // Create a new application context
                AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
                
                // Register configuration class (optional)
                context.register(AppConfig.class);
                
                // Register additional beans dynamically
                context.register(MyBean.class);
                
                // Refresh the context to apply the registrations
                context.refresh();
                
                // Retrieve the dynamically registered bean
                MyBean myBean = context.getBean(MyBean.class);
                myBean.doSomething();
                
                context.close();
            }
        }
            

What is NoUniqueBeanDefinitionException in Spring

NoUniqueBeanDefinitionException is a runtime exception in Spring that occurs when the application context contains multiple beans of the same type, and you try to retrieve a bean by type without specifying the bean's name or any further qualifier. In this case, Spring gets confused because there are multiple matching beans and it does not know which one to inject or retrieve. This can happen, for example, when multiple beans of the same class or interface are defined in the Spring container.

When Does This Exception Occur?

This exception occurs in the following scenarios:


Exception Message

The exception message typically looks like this:

org.springframework.beans.factory.NoUniqueBeanDefinitionException:
No qualifying bean of type 'com.example.MyService' available:
expected single matching bean but found 2: myService1,myService2

This message tells you that Spring expected one matching bean of type MyService, but it found two beans: myService1 and myService2.



How to Resolve This Exception?

To resolve this exception, you can take the following steps: