Understanding Spring Bean Scopes in SAP Hybris

Understanding Spring Bean Scopes in SAP Hybris

Spring’s bean scopes define the lifecycle and visibility of a bean within the Spring container. SAP Hybris, built on the Spring framework, leverages these scopes extensively for defining application behavior.

This guide explains the different bean scopes and how to use them effectively in SAP Hybris development.


Types of Bean Scopes in Spring

Spring supports several bean scopes. Below are the commonly used ones:

  1. Singleton (Default)
    A single instance per Spring container. The same instance is reused across the application.

  2. Prototype
    A new bean instance is created every time it is requested.

  3. Request
    A single bean instance is created per HTTP request. Suitable for web applications.

  4. Session
    A single bean instance is created per HTTP session. It persists for the duration of the session.

  5. Global Session
    Similar to session scope but used in portlet-based applications for global portlet sessions.

  6. Custom Scopes
    You can define custom scopes as needed.


How to Define Bean Scopes in Spring XML Configuration

Specify the scope attribute in the bean definition:

Singleton (Default Scope)

1
<bean id="singletonBean" class="com.mycompany.SingletonService" scope="singleton" />

Prototype

1
<bean id="prototypeBean" class="com.mycompany.PrototypeService" scope="prototype" />

Request Scope

1
<bean id="requestBean" class="com.mycompany.RequestService" scope="request" />

Session Scope

1
<bean id="sessionBean" class="com.mycompany.SessionService" scope="session" />

Usage in Java Config

You can use annotations to define bean scopes in Java-based configuration:

Singleton

1
2
3
4
5
@Component
@Scope("singleton")
public class SingletonService {
// Implementation
}

Prototype

1
2
3
4
5
@Component
@Scope("prototype")
public class PrototypeService {
// Implementation
}

Use Cases for Different Scopes in Hybris

Singleton

  • Use Case: Services that are stateless or shared across the application, such as DAOs or Facades.
  • Example: ProductService, CartService.

Prototype

  • Use Case: Beans requiring unique state for each use.
  • Example: Temporary objects used in batch processing.

Request

  • Use Case: Storing request-specific data, such as form submissions.
  • Example: Validation services or request-specific DTOs.

Session

  • Use Case: Managing session-specific data, such as logged-in user information.
  • Example: Session carts or user preferences.

Spring Scopes in SAP Hybris Extensions

In Hybris, Spring bean scopes can be configured in *-spring.xml files. Examples:

Configuring Singleton Bean in an Extension

1
2
3
<bean id="defaultCartService" class="com.mycompany.DefaultCartService" scope="singleton">
<property name="cartDao" ref="cartDao" />
</bean>

Using Prototype Beans in an Extension

1
<bean id="temporaryBatchProcessor" class="com.mycompany.BatchProcessor" scope="prototype" />

Custom Bean Scopes

Spring allows custom scope implementation. You can create and register custom scopes for specific needs.

Steps to Create a Custom Scope:

  1. Implement org.springframework.beans.factory.config.Scope.
  2. Register the scope in the Spring container.

Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public class CustomScope implements Scope {
private Map<String, Object> scopedObjects = new HashMap<>();

@Override
public Object get(String name, ObjectFactory<?> objectFactory) {
return scopedObjects.computeIfAbsent(name, k -> objectFactory.getObject());
}

@Override
public Object remove(String name) {
return scopedObjects.remove(name);
}

@Override
public void registerDestructionCallback(String name, Runnable callback) {
// Optional implementation
}

@Override
public Object resolveContextualObject(String key) {
return null;
}

@Override
public String getConversationId() {
return "custom";
}
}

Best Practices

  1. Choose the Scope Wisely
    Use the appropriate scope based on the bean’s lifecycle requirements.

  2. Avoid Stateful Singletons
    Do not store state in singleton beans unless absolutely necessary.

  3. Document Scope Usage
    Clearly document the reason for choosing a particular scope.

  4. Test for Memory Leaks
    Ensure session or request-scoped beans are cleaned up properly to avoid memory leaks.


Final Thoughts

Understanding and leveraging Spring’s bean scopes in SAP Hybris can help you design better, more maintainable applications. By choosing the right scope for the right use case, you can optimize performance, reduce resource usage, and improve scalability.

Happy Coding!