What is AOP? How we can use AOP in SAP Commerce(Hybris) to measure execution time of methods?
Aspect-oriented programming(AOP) is a programming paradigm which breaks down program logic into distinct parts so-called concerns. The key unit of modularity in OOP is the class, whereas in AOP the unit of modularity is the aspect.
Aspects enable the implementation of crosscutting concerns such as- transaction, logging, not central to business logic without cluttering the code core to its functionality. It does so by adding additional behaviour that is the advice to the existing code.
AOP helps to avoid code scattering and duplication due to cross cutting concerns, which aren’t well addressed by OO and give possibility to add new behavior to classes without having to modify their source code.
Common terminologies in AOP:
- Aspect — module which has a set of APIs providing cross-cutting requirements. It can be normal class configured through XML configuration or through regular classes annotated with @Aspect;
- Advice — it is the action taken by an aspect at a particular join-point(before or after);
- Joinpoint — possible points at which an advice can be applied (advised), will plug-in the AOP aspect;
- Pointcut — set of one or more join points where an advice should be executed;
- Weaving — the process of linking aspects with other application types or objects to create an advised object.
Types of Advice:
- before — run advice before the a method execution;
- after — run advice after the method execution;
- around — run advice before and after the advised method is called;
- after — returning — run advice afther the method execution only if method is completed;
- after — throwing — run advice after method execution only if methods throws exception.
How we can use AOP in SAP Commerce(Hybris) to measure execution time of methods?
I will show how we can measure all Prepare interceptors called in SAP Commerce, the same can be done for Populators, Filters and etc.
- Create class MethodExecutionTimeAspect
2. Then in your extension-spring.xml define the bean and aop config:
Around advice is a special advice that can control when and if a method is executed. This is true for around advices only, so they require an argument of type ProceedingJoinPoint, whereas other advices just use a plain JoinPoint.
We define the pointcut expression with: <aop:pointcut expression=”execution(
We define the advice with: <aop:around
To measure Populators in your project just replace: expression with:
expression=”execution(public * de.hybris.platform.converters.Populator+.populate(..))”/>
Some more examples with Before and After advices:
Logging after methods execution:
Logging before methods execution: