Spring Boot Tutorial

Spring Boot - Software Setup and Configuration (STS/Eclipse/IntelliJ)

Prerequisite (Spring Core Concepts)

Spring Boot Core

Spring Boot with REST API

Spring Boot with Database and Data JPA

Spring Boot with Kafka

Spring Boot with AOP

Custom Bean Scope in Spring

In Spring, apart from the predefined bean scopes (singleton, prototype, request, session, application), you can also define custom scopes.

Creating a custom scope requires two primary steps:

  1. Implementing the org.springframework.beans.factory.config.Scope interface.
  2. Registering the custom scope in the Spring context.

Let's walk through these steps.

1. Implementing the Scope interface:

Suppose you want to create a custom scope called threadScope, where each thread gets its instance of a bean.

import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.config.Scope;

import java.util.HashMap;
import java.util.Map;

public class ThreadScope implements Scope {

    private final ThreadLocal<Map<String, Object>> threadScope = 
        ThreadLocal.withInitial(HashMap::new);

    @Override
    public Object get(String name, ObjectFactory<?> objectFactory) {
        Map<String, Object> scope = threadScope.get();
        Object obj = scope.get(name);
        if (obj == null) {
            obj = objectFactory.getObject();
            scope.put(name, obj);
        }
        return obj;
    }

    @Override
    public Object remove(String name) {
        Map<String, Object> scope = threadScope.get();
        return scope.remove(name);
    }

    @Override
    public void registerDestructionCallback(String name, Runnable callback) {
        // For this example, we are not registering any destruction callbacks
    }

    @Override
    public Object resolveContextualObject(String key) {
        return null; // Not needed for this simple example
    }

    @Override
    public String getConversationId() {
        return String.valueOf(Thread.currentThread().getId());
    }
}

2. Registering the custom scope:

This can be done in Java configuration or XML configuration.

  • Java Configuration:

    @Configuration
    public class AppConfig {
    
        @Bean
        public static CustomScopeConfigurer customScopeConfigurer() {
            CustomScopeConfigurer configurer = new CustomScopeConfigurer();
            configurer.addScope("threadScope", new ThreadScope());
            return configurer;
        }
    
        @Bean
        @Scope("threadScope")
        public MyBean myBean() {
            return new MyBean();
        }
    }
    
  • XML Configuration:

    <beans ...>
        <bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
            <property name="scopes">
                <map>
                    <entry key="threadScope">
                        <bean class="com.example.ThreadScope"/>
                    </entry>
                </map>
            </property>
        </bean>
    
        <bean id="myBean" class="com.example.MyBean" scope="threadScope"/>
    </beans>
    

With the custom threadScope registered, you can now annotate beans with @Scope("threadScope"), and they'll be scoped to the lifecycle of a thread.

Remember that creating custom scopes can add complexity to your application. Always ensure you have a valid reason to deviate from the built-in scopes provided by Spring.

  1. Creating custom bean scopes in Spring:

    • Description: Spring provides several standard bean scopes (singleton, prototype, etc.), but you can create custom scopes tailored to your application's needs.
    • Code:
      public interface CustomScope extends Scope {
          // Custom scope methods
      }
      
  2. Defining a custom scope for Spring beans:

    • Description: Define a custom scope by implementing the Scope interface.
    • Code:
      public class MyCustomScope implements Scope {
          // Implement custom scope methods
      }
      
  3. Configuring custom bean scopes in Spring XML:

    • Description: Configure custom bean scopes in XML-based Spring configuration.
    • Code:
      <bean class="com.example.MyCustomScope"/>
      
  4. Custom bean scoping in annotation-based configuration in Spring:

    • Description: Achieve custom bean scoping using annotations and Java-based configuration.
    • Code:
      @Scope("myCustomScope")
      @Component
      public class MyScopedBean {
          // Bean definition
      }