AOP is a programming paradigm that aims to increase modularity by allowing the separation of cross-cutting concerns. It does this by adding additional behavior to existing code without modifying the code itself.
public class SampleAdder {
public int add(int a, int b) {
return a + b;
}
}
An aspect is a modularization of a concern that cuts across multiple classes. Unified logging can be an example of such cross-cutting concern.
public class AdderAfterReturnAspect {
private Logger logger = LoggerFactory.getLogger(this.getClass());
public void afterReturn(Object returnValue) throws Throwable {
logger.info("value return was {}", returnValue);
}
}
A Joinpoint is a point during the execution of a program, such as the execution of a method or the handling of an exception.
A Pointcut is a predicate that helps match an Advice to be applied by an Aspect at a particular JoinPoint.
We often associate the Advice with a Pointcut expression, and it runs at any Joinpoint matched by the Pointcut.
An Advice is an action taken by an aspect at a particular Joinpoint.
@Before
annotation mark.@AfterReturning
annotation mark.@AfterThrowing
annotation mark.@After
annotation mark.@Around
annotation mark.<bean id="sampleAdder" class="org.baeldung.logger.SampleAdder" />
<bean id="doAfterReturningAspect"
class="org.baeldung.logger.AdderAfterReturnAspect" />
<aop:config>
<aop:aspect id="aspects" ref="doAfterReturningAspect">
<aop:pointcut id="pointCutAfterReturning" expression=
"execution(* org.baeldung.logger.SampleAdder+.*(..))"/>
<aop:after-returning method="afterReturn"
returning="returnValue" pointcut-ref="pointCutAfterReturning"/>
</aop:aspect>
</aop:config>
simpleAdder
, which represents an instance of a Business Object.AdderAfterReturnAspect
.config
tag, we define the class that represents an aspect. Then we give it a reference of doAfterReturningAspect
, an aspect bean that we created.pointcut
tag. The pointcut used in the example above is execution(* org.baeldung.logger.SampleAdder+.*(..))
, which means apply an advice on any method within the SampleAdder
class that accepts any number of arguments and returns any value type.after-returning
advice. We defined this in our Aspect AdderAfterReturnAspect
by executing the afterReturn
method that we defined using the attribute method.