PointCut in Spring
In this tutorial, we are going to discuss PointCut in Spring. PointCut defines what Joinpoints Advices have to be applied instead of defining advice at all join points.
If we want to use PointCuts in AOP based applications, we have to configure those pointcuts in Spring configuration File. To configure Pointcuts in the configuration file then we have to use the following two.
- Static Pointcut
- Dynamic Pointcut
1. Static Pointcut
Static pointcuts define advice that is always executed. Static pointcuts are based on method and target class and cannot consider the method’s arguments. Static pointcuts are sufficient – and best – for most usages. Spring can evaluate a static pointcut only once when a method is first invoked: after that, there is no need to re-evaluate the pointcut with each method invocation.
To represent Pointcuts, the Spring framework has provided a predefined interface in the form of “org.springframework.aop.PointCut“.
Spring Framework has provided the following Implementation classes for org.springframework.aop.PointCut interface.
- NameMatchMethodPointcut
- Perl5RegexpMethodPointcut
- JdkRegexpMethodPointcut
2. Dynamic Pointcut
Dynamic pointcuts determine if advice should be executed by examining the runtime method arguments.
Dynamic pointcuts are costlier to evaluate than static pointcuts. They take into account method arguments, as well as static information. This means that they must be evaluated with every method invocation; the result cannot be cached, as arguments will vary.
To represent Dynamic Pointcut Spring has provided the following predefined class.
- ControlFlowPointcut
- DynamicMethodMatcherPointcut
If we want to use Pointcuts in Spring applications, we have to configure Pointcut and Advisor in the spring configuration file.
In spring applications, we will use “DefaultPointCutAdvosor” to suggest the advice to the Pointcuts.
Where if we want to use NameMatchMethodPointcut, then we have to use the “mappedNames” property of type “array”, and we must provide business method names as values to which we want to apply advice.
<bean id="pointcut" class="org.springframework.aop.support.NameMatchMethodPointcut">
<property name="mappedNames">
<array>
<value>displayEmployee</value>
<value>getEmployeeDetails</value>
</array>
</property>
</bean>
Where If we want to use “Perl5RegexpMethodPointcut” and “JdkRegexpMethodPointcut” in spring applications, then we have to use a property like “pattern” of list type with different patterns.
<bean id="pointcut" class="org.springframework.aop.support.Perl5RegexpMethodPointcut">
<property name="patterns">
<list>
<value>.*Employee.*</value>
</list>
</property>
</bean>
If we want to use DefaultPointcutAdvisor in spring applications, we have to use “pointcut” and “advice” properties.
<bean id="advisor" class="org.springframework.aop.support.DefaultPointcutAdvisor">
<property name="pointcut" ref="pointcut"/>
<property name="advice" ref="validatorAdvice"/>
</bean>