top of page

Overview

​

Model interceptor is a powerful mechanism that allows you to modify or validate data before it's saved to the database or retrieved from the database. Model interceptors are commonly used to enforce business rules, perform data validation, or implement custom logic on Hybris models. The life cycle of a model interceptor typically involves several stages: creation, registration, execution, and disposal.

​

Hybris model has a life cycle which is managed by ModelService. ModelService contains methods like Create, Update, Save, load and Remove which are utilized at different stages of the model life cycle. 

​

Use of interceptor : 

​

1) Data Validation: Interceptors can be used to validate data before it's saved to the database. For instance, you can ensure that mandatory fields are filled, check for valid formats, or enforce business rules related to the data.

​

2) Data Transformation: Interceptors enable you to transform or preprocess data before it's persisted. This can include formatting dates, converting units, or modifying values based on specific conditions.

​

3) Logging and Auditing: You can use interceptors to log changes to models, providing an audit trail of who made what changes and when. This is essential for tracking data modifications for compliance or debugging purposes.

​

4) Security and Permissions: Interceptors can enforce security and permissions checks. For example, you can ensure that a user has the appropriate rights to modify a specific model before allowing the operation to proceed.

​

5) Default Values: Set default values for attributes when creating new instances of a model. This is useful for providing sensible defaults to users or ensuring consistency in data.

 

​

​

Interceptor Type and Customization

​

1) Init Defaults interceptor: The InitDefaultsInterceptor is a special type of model interceptor that is automatically invoked when a new instance of a model is created. Its primary purpose is to set default values for attributes in the model before it's saved to the database. This is particularly useful for ensuring that newly created objects have initial values for certain attributes.

 

This is called when a model needs to be filled with its default values. This will be called implicitly when modelService's  create or  initDefaults method is called.

​

Here's an example of how to create and use an InitDefaultsInterceptor in Hybris:

​

  • Create the Interceptor Class: You need to create a Java class that extends AbstractInterceptor and implements the InitDefaultsInterceptor interface for the specific model type you want to apply defaults to. Let's assume we want to set a default value for a ProductModel attribute called inStock.

​

import de.hybris.platform.servicelayer.interceptor.InterceptorContext;
import de.hybris.platform.servicelayer.interceptor.InitDefaultsInterceptor;
import de.hybris.platform.core.model.product.ProductModel;

public class CustomProductInitDefaultsInterceptor implements InitDefaultsInterceptor<ProductModel> {

    @Override
    public void onInitDefaults(ProductModel product, InterceptorContext context) {
        // Set the default value for the 'inStock' attribute
        product.setInStock(Boolean.TRUE);
    }

}

 

  • Register the Interceptor: Next, you need to register your interceptor in the items.xml file associated with your extension.<

 

<!-- Defining Spring bean for <Interceptor -->

<bean id="customProductInitDefaultsInterceptor" class="de.hybris.platform.product.interceptor.CustomProductInitDefaultsInterceptor"/>

​

<!-- Mapping Interceptor and model class-->

<bean id="customProductInitDefaultsInterceptorMapping" class="de.hybris.platform.servicelayer.interceptor.impl.InterceptorMapping">

        <property name="interceptor" ref="customProductInitDefaultsInterceptor"/>

        <property name="typeCode" value="Product"/>

    </bean>

​

  • Use the Default Values: Now, whenever a new ProductModel instance is created, the onInitDefaults method of your interceptor will be automatically invoked, and it will set the default value for the inStock attribute.

 

ProductModel newProduct = modelService.create(ProductModel.class);

boolean isInStock = newProduct.getInStock();

​

​

​

​

​

2) Prepare Interceptor: The PrepareInterceptor is a type of model interceptor that allows you to perform custom actions on a model instance before it is saved to the database. This interceptor is commonly used for data preparation, validation, or any other logic that should be executed just before saving the model.

This is called before a model is saved to the database and before it is validated by Validate interceptors.

​

Here's an example of how to create and use a PrepareInterceptor in Hybris:

​

  • Create the Interceptor Class: First, you need to create a Java class that extends AbstractInterceptor and implements the PrepareInterceptor interface for the specific model type you want to work with. Let's assume we have a custom model called CustomProductModel, and we want to create a PrepareInterceptor for it.

​

import de.hybris.platform.servicelayer.interceptor.InterceptorContext;
import de.hybris.platform.servicelayer.interceptor.PrepareInterceptor;
import com.example.model.CustomProductModel;

public class CustomProductPrepareInterceptor implements PrepareInterceptor<CustomProductModel> {

    @Override
    public void onPrepare(CustomProductModel customProduct, InterceptorContext context) {
        // Perform custom preparation logic here
        // For example, you can validate data or set additional attributes.
        if (customProduct.getPrice() < 0) {
            throw new InterceptorException("Price cannot be negative.");
        }
    }
}

​

  • Register the Interceptor: Next, you need to register your interceptor in the xml file associated with your extension.

​​

<!-- Defining Spring bean for <Interceptor -->

<bean id="customProductPrepareInterceptor" class="de.hybris.platform.product.interceptor.CustomProductPrepareInterceptor"/>

​

<!-- Mapping Interceptor and model class-->

<bean id="customProductPrepareInterceptorMapping" class="de.hybris.platform.servicelayer.interceptor.impl.InterceptorMapping">

        <property name="interceptor" ref="customProductPrepareInterceptor"/>

        <property name="typeCode" value="CustomProduct"/>

    </bean>

​​

  • Use the Interceptor: Now, when you save an instance of CustomProductModel, the onPrepare method of your interceptor will be automatically invoked before the model is persisted to the database.

​​

CustomProductModel customProduct = new CustomProductModel();

customProduct.setCode("12345");

customProduct.setPrice(10.0);

try {

modelService.save(customProduct);

}

catch (InterceptorException e)

{ // Handle the exception, e.g., log an error message or display a user-friendly error. }

​

​

​

​

​

3) Validate interceptor: Validate interceptor is a type of model interceptor that is used to perform data validation on a model instance before it is saved to the database. This is a crucial step to ensure that the data being persisted adheres to the defined business rules and constraints.

​

This is called before a model is saved to the database after is been prepared by the Prepare interceptors.

 

Here's an example of how to create and use a validate interceptor in Hybris:

​

  • Create the Validate Interceptor Class: You need to create a Java class that extends AbstractInterceptor and implements the ValidateInterceptor interface for the specific model type you want to validate. Let's assume you have a custom model called CustomProductModel, and you want to create a validate interceptor for it.

​

import de.hybris.platform.servicelayer.interceptor.AbstractInterceptor;
import de.hybris.platform.servicelayer.interceptor.InterceptorContext;
import de.hybris.platform.servicelayer.interceptor.ValidateInterceptor;
import com.example.model.CustomProductModel;

public class CustomProductValidateInterceptor extends AbstractInterceptor<CustomProductModel> implements ValidateInterceptor<CustomProductModel> {

    @Override
    public void onValidate(CustomProductModel customProduct, InterceptorContext context) {
        // Perform custom validation logic here
        if (customProduct.getPrice() < 0) {
            throw new InterceptorException("Price cannot be negative.");
        }

        // Add more validation checks as needed
    }
}

​

  • Register the Interceptor: Next, you need to register your validate interceptor in the xml file associated with your extension.

 

<!-- Defining Spring bean for <Interceptor -->

<bean id="customProductValidateInterceptor" class="de.hybris.platform.product.interceptor.CustomProductValidateInterceptor"/>

​

<!-- Mapping Interceptor and model class-->

<bean id="customProductValidateInterceptorMapping" class="de.hybris.platform.servicelayer.interceptor.impl.InterceptorMapping">

        <property name="interceptor" ref="customProductValidateInterceptor"/>

        <property name="typeCode" value="CustomProduct"/>

    </bean>

​

​

  • Use the Interceptor: Now, whenever you attempt to save an instance of CustomProductModel, the onValidate method of your interceptor will be automatically invoked before the model is persisted to the database.

​​

CustomProductModel customProduct = new CustomProductModel();
customProduct.setCode("12345");
customProduct.setPrice(-10.0);

try {
    modelService.save(customProduct);
} catch (InterceptorException e) {
    // Handle the validation exception, e.g., log an error message or display a user-friendly error.
}

 

​

​

 

4) Load Interceptor: Load interceptor is a type of model interceptor that allows you to customize the behavior when an object is loaded from the database. This interceptor is particularly useful for initializing or modifying the loaded data before it is used in your application.

​

This is called when we retrieve the model from the database.

​

Here's an example of how to create and use a load interceptor in Hybris:

​

  • Create the Load Interceptor Class: You need to create a Java class that extends AbstractInterceptor and implements the LoadInterceptor interface for the specific model type you want to work with. Let's assume you have a custom model called CustomProductModel, and you want to create a load interceptor for it.

​

import de.hybris.platform.servicelayer.interceptor.AbstractInterceptor;
import de.hybris.platform.servicelayer.interceptor.InterceptorContext;
import de.hybris.platform.servicelayer.interceptor.LoadInterceptor;
import com.example.model.CustomProductModel;

public class CustomProductLoadInterceptor extends AbstractInterceptor<CustomProductModel> implements LoadInterceptor<CustomProductModel> {

    @Override
    public void onLoad(CustomProductModel customProduct, InterceptorContext context) {
        // Perform custom load logic here
        customProduct.setDisplayName("Loaded: " + customProduct.getName());
    }
}

 

  • Register the Interceptor:  Next, you need to register your interceptor in the xml file associated with your extension.

​​

<!-- Defining Spring bean for <Interceptor -->

<bean id="customProductLoadInterceptor" class="de.hybris.platform.product.interceptor.CustomProductLoadInterceptor"/>

​

<!-- Mapping Interceptor and model class-->

<bean id="customProductLoadInterceptorMapping" class="de.hybris.platform.servicelayer.interceptor.impl.InterceptorMapping">

        <property name="interceptor" ref="customProductLoadInterceptor"/>

        <property name="typeCode" value="CustomProduct"/>

    </bean>

​​

  • Use the Interceptor: Now, when you retrieve an instance of CustomProductModel from the database, the onLoad method of your interceptor will be automatically invoked, allowing you to modify the loaded data.


CustomProductModel loadedProduct = productService.getProductForCode("12345");

String displayName = loadedProduct.getDisplayName(); // This will include "Loaded: "

​

​

​

​

5) Remove Interceptor: Remove interceptors in Hybris are a type of model interceptor that allows you to customize the behavior when an object is removed or deleted from the system. They are triggered when an instance of a model is being deleted, and they enable you to perform actions or validation specific to the removal process.

​

This is called before a model is removed/deleted from the database.

​

Here's an explanation of remove interceptors with an example:

​

You have a custom model called OrderModel, which represents an order in your e-commerce system. When an order is deleted, you want to ensure that all associated items in the order are also removed from the system. You can create a remove interceptor to handle this logic.

​

  • Create the Interceptor Class:  We've created a custom CustomOrderRemoveInterceptor that extends AbstractRemoveInterceptor and is specific to the OrderModel. In the onRemove method, we iterate through all the associated OrderItemModel instances and delete them when an OrderModel is removed.

​​

import de.hybris.platform.servicelayer.interceptor.AbstractRemoveInterceptor;
import de.hybris.platform.servicelayer.interceptor.InterceptorContext;
import com.example.model.OrderModel;
import com.example.model.OrderItemModel;

public class CustomOrderRemoveInterceptor extends AbstractRemoveInterceptor<OrderModel> {

    @Override
    public void onRemove(OrderModel order, InterceptorContext context) {
        // Perform custom removal logic here
        // For example, delete all associated order items
        for (OrderItemModel orderItem : order.getOrderItems()) {
            modelService.remove(orderItem);
        }
    }
}

 

  • Registering the Remove Interceptor: To make this interceptor effective, you should register it in the xml file associated with your extension:

 

<!-- Defining Spring bean for <Interceptor -->

<bean id="customOrderRemoveInterceptor" class="de.hybris.platform.order.interceptor.CustomOrderRemoveInterceptor"/>

​

<!-- Mapping Interceptor and model class-->

<bean id="customOrderRemoveInterceptorMapping" class="de.hybris.platform.servicelayer.interceptor.impl.InterceptorMapping">

        <property name="interceptor" ref="customOrderRemoveInterceptor"/>

        <property name="typeCode" value="CustomProduct"/>

    </bean>

​

  • Using the Remove Interceptor: Now, when you delete an OrderModel instance in your application, the CustomOrderRemoveInterceptor will automatically execute, ensuring that associated OrderItemModel instances are also removed.

​​

OrderModel order = orderService.getOrderByCode("12345");
modelService.remove(order); // This will trigger the remove interceptor

 

About the Author

 

Piyush Singh is a seasoned technology enthusiast and educator with a passion for making complex concepts accessible to everyone. With over 10 years of experience in the tech industry working as consultant,  Piyush specializes in Java, Sap Hybris technology and has a knack for breaking down intricate topics into easy-to-follow tutorials.

​​​​​​​

   Connect with Author

LinkedIn

Email

​

​

bottom of page