Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources

Spring Beans

In the Spring Framework, beans are the objects that form the backbone of your application and are managed by the Spring IoC container. This guide covers the key concepts, lifecycle, and configuration of Spring beans.

What is a Spring Bean?

A Spring bean is an object that is instantiated, assembled, and managed by the Spring IoC container. Beans are defined in the Spring configuration file (XML or Java-based) and are typically used to represent the services and data model of your application.

Bean Definition

Beans are defined in the Spring configuration file. You can define beans using XML configuration, annotations, or Java-based configuration.

XML-based Configuration

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="myBean" class="com.example.MyBean">
        <property name="dependency" ref="myDependency"/>
    </bean>

    <bean id="myDependency" class="com.example.MyDependency"/>
</beans>

Annotation-based Configuration

// MyBean.java
package com.example;

import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Autowired;

@Component
public class MyBean {
    private final MyDependency myDependency;

    @Autowired
    public MyBean(MyDependency myDependency) {
        this.myDependency = myDependency;
    }

    public void doSomething() {
        myDependency.action();
    }
}

// MyDependency.java
package com.example;

import org.springframework.stereotype.Component;

@Component
public class MyDependency {
    public void action() {
        System.out.println("Dependency action");
    }
}

Java-based Configuration

// AppConfig.java
package com.example;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

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

    @Bean
    public MyDependency myDependency() {
        return new MyDependency();
    }
}

Bean Lifecycle

Spring beans go through several stages during their lifecycle, managed by the IoC container. The key stages are:

  • Instantiation: The container creates a bean instance using the configured constructor or factory method.
  • Population of Properties: The container injects the bean's dependencies, either via constructor injection, setter injection, or field injection.
  • Initialization: The container calls the bean's afterPropertiesSet method (if it implements InitializingBean) or a custom init method (if specified).
  • Ready for Use: The bean is ready to be used by the application.
  • Destruction: The container calls the bean's destroy method (if it implements DisposableBean) or a custom destroy method (if specified) before it is removed from the container.
// Example of bean lifecycle methods
@Component
public class MyBean implements InitializingBean, DisposableBean {
    @Override
    public void afterPropertiesSet() throws Exception {
        // Initialization logic
        System.out.println("Bean is initialized");
    }

    @Override
    public void destroy() throws Exception {
        // Cleanup logic
        System.out.println("Bean is destroyed");
    }
}

Bean Scopes

Spring supports several bean scopes to define the lifecycle and visibility of beans:

  • Singleton: A single instance of the bean is created and shared across the entire Spring container (default scope).
  • Prototype: A new instance of the bean is created every time it is requested.
  • Request: A single instance of the bean is created for each HTTP request (web applications only).
  • Session: A single instance of the bean is created for each HTTP session (web applications only).
  • Global Session: A single instance of the bean is created for the global HTTP session (portlet applications only).
// XML-based configuration (bean scope)
<bean id="myBean" class="com.example.MyBean" scope="prototype"/>

// Java-based configuration (bean scope)
@Bean
@Scope("prototype")
public MyBean myBean() {
    return new MyBean(myDependency());
}

Bean Autowiring

Spring provides several modes for autowiring bean dependencies:

  • No: No autowiring is performed. Dependencies must be explicitly specified.
  • ByName: Autowires by property name. The container looks for a bean with the same name as the property to be autowired.
  • ByType: Autowires by property type. The container looks for a bean with the same type as the property to be autowired.
  • Constructor: Autowires by constructor. The container looks for a matching constructor with arguments that can be autowired by type.
  • Autowired: Uses annotations to indicate that a property, method, or constructor should be autowired.
// Example of autowiring using annotations
@Component
public class MyBean {
    @Autowired
    private MyDependency myDependency;

    public void doSomething() {
        myDependency.action();
    }
}

Key Points

  • Spring beans are the backbone objects managed by the Spring IoC container.
  • Beans can be defined using XML configuration, annotations, or Java-based configuration.
  • Spring beans go through a lifecycle managed by the IoC container, including instantiation, property population, initialization, and destruction.
  • Spring supports several bean scopes to define the lifecycle and visibility of beans.
  • Spring provides various modes for autowiring bean dependencies, including by name, by type, by constructor, and using annotations.

Conclusion

Spring beans are fundamental to the Spring Framework, representing the services and data model of your application. By understanding bean definition, lifecycle, scopes, and autowiring, you can effectively manage your application's components and dependencies. Happy coding!