Module 4 - Spring and AOP Final
Module 4 - Spring and AOP Final
Anytime, anywhere
Class ⇒ object
(define) (key unit data represent class)
● There are various common good examples of aspects like logging, auditing,
declarative transactions, security, caching, etc.
AOP
● The key unit of modularity in OOP is the class, whereas in AOP the unit of modularity
is the aspect.
● Dependency Injection helps you decouple your application objects from each other and
AOP helps you decouple cross-cutting concerns from the objects that they affect. AOP is
like triggers.
● Spring AOP module provides interceptors to intercept an application. For example, when
a method is executed, you can add extra functionality before or after the method
execution.
● AOP the unit of modularity is the aspect.
JUST FOR REFERENCE :
Modular programming is the process of subdividing a computer program into separate
sub-programs. A module is a separate software component. It can often be used in a variety of
applications and functions with other components of the system.
● Some programs might have thousands or millions of lines and to manage such programs it
becomes quite difficult as there might be too many of syntax errors or logical errors present
in the program, so to manage such type of programs concept of modular programming
approached.
Need of spring AOP
The Spring AOP provides the pluggable way of dynamically adding the additional
concern before, after or around the actual logic. Suppose there are 10 methods in a
class as given below:
The Scenario: You have to maintain the log and send the notification after calling
methods starting from m.
A problem without using the AOP: You can call methods which maintain logs and
sends the notification from the methods starting with m. For that, you need to write
code for all the 5 methods.
The solution with Aspect Oriented Programming: You don’t have to call methods
from the method. You can define additional concerns like maintaining a log,
sending notification etc. as a method of a class. Its entry is given in the xml file.
In future, if client says to remove the notifier functionality, we need to
change only in the xml file. So, maintenance is easy in AOP.
Where to use Spring Aspect Oriented Programming
Join point : This represents a point in your application where you can plug-in the AOP
aspect. You can also say, it is the actual place in the application where an action will be taken
using Spring AOP framework.
● An application has thousands of opportunities or points to apply Advice. These points are
known as join points. For example – Advice can be applied at every invocation of a
method or exception be thrown or at various other points. But Spring AOP currently
supports only method execution join points (advising the execution of methods on Spring
beans).
Join point is any point in your program such as method execution, exception handling,
field access etc. Spring supports only method execution join points
Advice :
Advice represents an action taken by an aspect at a particular join point. There
are different types of advices:
● After (finally) Advice: it executes after a join point regardless of join point exit
whether normally or exceptional return.
4. Advice is associated with a pointcut expression and runs at any join point
matched by the pointcut.
1. XML Schema based : Aspects are implemented using the regular classes along with
XML based configuration.
2. @AspectJ based : @AspectJ refers to a style of declaring aspects as regular Java classes
annotated with Java 5 annotations.
1. XML Schema Based AOP with Spring
To use the AOP namespace tags described in this section, you need to import the
springAOP schema as described −
Here "aBean" will be configured and dependency injected just like any other Spring bean as you
have seen in the previous chapters.
Note :Aspect: An aspect is a class that implements enterprise application concerns that cut across
multiple classes, such as transaction management. Aspects can be a normal class configured through Spring
XML configuration or we can use Spring AspectJ integration to define a class as Aspect using @Aspect
annotation.
Declaring a pointcut
A pointcut helps in determining the join points (i.e methods) of interest to be executed
with different advices. While working with XML Schema-based configuration, pointcut will be
defined as follows −
<aop:config>
<aop:aspect id = "myAspect" ref = "aBean">
<aop:pointcut id = "businessService"
expression = "execution(* com.xyz.myapp.service.*.*(..))"/>
...
</aop:aspect>
</aop:config>
<bean id = "aBean" class = "...">
...
</bean>
Note : Joinpoint is a point of execution of the program, such as the execution of a method or
the handling of an exception. In Spring AOP, a joinpoint always represents a method execution.
Pointcut is a predicate or expression that matches join points.
Declaring pointcut example
The following example defines a pointcut named 'businessService' that will match the execution of
getName() method available in the Student class under the package com.tutorialspoint −
Declaring Advices
You can declare any of the five
advices inside an <aop:aspect>
using the <aop:{ADVICE NAME}>
1 Create a project with a name SpringExample and create a package under the src
folder in the created project.
For example, the following pointcut expression matches all of the methods declared in
the EmployeeManager class. The preceding wildcard matches methods with any
modifier (public, protected, and private) and any return type. The two dots in the
argument list match any number of arguments.
execution(* com.howtodoinjava.EmployeeManager.*(..))
2.Match all methods within a class within same package
You can omit the package name if the target class or interface is located in the
same package as this aspect.
execution(* EmployeeManager.*(..))
Use public keyword in start, and use * to match any return type(void,int,float,string).
execution(public * EmployeeManager.*(..))
4.Match all public methods in EmployeeManager with return type int
5.Match all public methods in EmployeeManager with return type int and first
parameter as String
Use public keyword and return type in start. Also, specify your first parameter as well. Rest
parameters can be matched through two dots.
You will also need the following AspectJ libraries on the classpath of your application.
These libraries are available in the 'lib' directory of an AspectJ installation, otherwise you
can download them from the internet.
● aspectjrt.jar
● aspectjweaver.jar
● aspectj.jar
● aopalliance.jar
Declaring an aspect
Aspects classes are like any other normal bean and may have methods and fields just
like any other class, except that they will be annotated with @Aspect as follows −
package org.xyz;
import org.aspectj.lang.annotation.Aspect;
@Aspect //annotation
public class AspectModule {
}
They will be configured in XML like any other bean as follows −
<bean id = "myAspect" class = "org.xyz.AspectModule">
<!-- configure properties of aspect here as normal -->
</bean>
Declaring a pointcut
A pointcut helps in determining the join points (ie methods) of interest to be executed
with different advices. While working with @AspectJ-based configuration, pointcut
declaration has two parts −
The following example defines a pointcut named 'getname' that will match the execution of
getName() method available in the Student class under the package com.tutorialspoint −
import org.aspectj.lang.annotation.Pointcut;
@Pointcut("execution(* com.tutorialspoint.Student.getName(..))")
private void getname() {}
Declaring advices
You can declare any of the five advices using @{ADVICE-NAME} annotations as given in the code
snippet. This assumes that you already have defined a pointcut signature method businessService()
−
@After("businessService()")
public void doAfterTask(){ … }
@Around("businessService()")
public void doAroundTask(){ … }
You can define a pointcut inline for any of the advices. Following is an example to define
inline pointcut for before advice −
@Before("execution(* com.xyz.myapp.service.*.*(..))")
public doBeforeTask(){
…}
@AspectJ Based AOP Complete Example :
package com.tutorialspoint;
@Aspect
public class Logging {
@Pointcut("execution(* com.tutorialspoint.*.*(..))")
private void selectAll(){}
@Before("selectAll()") Logging.java file
1. @Before declares the before advice. It is applied before calling the actual method.
2. @After declares the after advice. It is applied after calling the actual method and before returning
result.
3. @AfterReturning declares the after returning advice. It is applied after calling the actual method
and before returning result. But you can get the result value in the advice.
4. @Around declares the around advice. It is applied before and after calling the actual method.
5. @AfterThrowing declares the throws advice. It is applied if actual method throws exception.
Understanding Pointcut
The @Pointcut annotation is used to define the pointcut. We can refer the pointcut
expression by name also. Let's see the simple example of pointcut expression.
It will be applied on all the methods of Operation class regardless of return type.
Understanding Pointcut Expressions
Let's try the understand the pointcut expressions by the examples given below:
The primary Spring PCD is execution, which matches method execution join points:
@Pointcut("execution(public String
com.baeldung.pointcutadvice.dao.FooDao.findById(Long))")
This example pointcut will exactly match the execution of the findById method of the FooDao
class. This works, but it's not very flexible. Suppose we'd like to match all the methods of the
FooDao class, which may have different signatures, return types, and arguments. To achieve
this, we can use wildcards:
@Pointcut("execution(*
com.baeldung.pointcutadvice.dao.FooDao.*(..))")
Here, the first wildcard matches any return value, the second matches any method name, and
the (..) pattern matches any number of parameters (zero or more).
within
Another way to achieve the same result as the previous section is by using the within
PCD, which limits matching to join points of certain types:
@Pointcut("within(com.baeldung.pointcutadvice.dao.FooDao)")
We can also match any type within the com.baeldung package or a sub-package:
@Pointcut("within(com.baeldung..*)")
this and target
this limits matching to join points where the bean reference is an instance of the given type, while
target limits matching to join points where the target object is an instance of the given type. The
former works when Spring AOP creates a CGLIB-based proxy, and the latter is used when a JDK-based
proxy is created. Suppose that the target class implements an interface:
In this case, Spring AOP will use the JDK-based proxy, and we should use the target PCD because the
proxied object will be an instance of the Proxy class and implement the BarDao interface:
@Pointcut("target(com.baeldung.pointcutadvice.dao.BarDao)")
On the other hand, if FooDao doesn't implement any interface, or the proxyTargetClass property is set to
true, then the proxied object will be a subclass of FooDao and we can use the this PCD:
@Pointcut("this(com.baeldung.pointcutadvice.dao.FooDao)")
args
@Pointcut("execution(* *..find*(Long))")
This pointcut matches any method that starts with find and has only one parameter
of type Long. If we want to match a method with any number of parameters, but still
having the fist parameter of type Long, we can use the following expression:
@Pointcut("execution(* *..find*(Long,..))")
@target
The @target PCD (not to be confused with the target PCD described above) limits
matching to join points where the class of the executing object has an annotation of
the given type:
@Pointcut("@target(org.springframework.stereotype.Repository)
")
@within
This PCD limits matching to join points within types that have the given annotation:
@Pointcut("@within(org.springframework.stereotype.Repository)")
@Pointcut("within(@org.springframework.stereotype.Repository
*)")
Supported Pointcut Designators
● execution – for matching method execution join points. This is the most widely used
PCD.//d1
● within – for matching methods of classes within certain types e.g. classes within a
package. //2
● @within – for matching to join points within types (target object class) that have the
given annotation.//a
● this – for matching to join points (the execution of methods) where the bean reference
(Spring AOP proxy) is an instance of the given type.//d3
● target – for matching with the target object of the specific instance type.//d4
● @target – for matching with the target object annotated with a specific annotation.
Supported Pointcut Designators
● args – for matching with methods where its arguments are of a specific type.//d5
● @args – for matching with methods where its arguments are annotated with a specific
annotation.
● @annotation (custom annotation concept)– for matching to join points where the subject
(method) of the Joinpoint has the given annotation.
● bean (idOrNameOfBean) – This PCD lets you limit the matching of join points to a particular
named Spring bean or to a set of named Spring beans (when using wildcards).//d6
● @Pointcut("bean(student)(* Employee.*(..))")
AspectJ provides several other designators which are not supported in Spring AOP, only the above
mentioned PCD are supported.
Combining Pointcut Expressions
You can combine multiple pointcut expressions by using AND – &&, OR – || and NOT – !. You can also
refer to pointcut expressions by name. The following example shows the same:
@Pointcut("execution(public * *(..))")
private void anyPublicOperation() {} //p1
@Pointcut("within(com.jsbd.trading..*)")
private void inTrading() {} //p2
throws-pattern?)
Similarly, the @within is used for matching with join points (method execution) where the declared class of
the target object has a given annotation.
c. The this designator
It limits the matching to join points (the execution of methods) where the bean reference
(Spring AOP proxy) is an instance of the given type.
For example, match with any join point (method execution) where the proxy implements the
AccountService interface.
"this(com.jbd.service.AccountService)"
d. The target and @target designators
The target designator limits matching to join points (the execution of methods) where the target
object (application object being proxied) is an instance of the given type. e.g. when the target
object implements a specific interface.
Example, any join point where the target object implements the AccountService interface.
"target(com.jbd.service.AccountService)"
Similarly, the @target is used to Limit matching to join points (the execution of methods) where the
class of the executing object has an annotation of the given type.
Example, any join point where the target object has a @Transactional annotation.
"@target(org.springframework.transaction.annotation.Transactional)"
Spring AOP - Proxy
So far, we've declared aspects using <aop:config> or < aop:aspectj-autoproxy>. We can create a
proxy programmatically as well as invoke the aspects programmatically using the proxy object.
SYNTAX:
Where,
PointCut annotation
Before annotation
OUTPUT : ?
❏ Annotations. (@Aspect,@Before,@After…)
❏ Ref : 1. https://www.javatpoint.com/spring-aop-aspectj-annotation-example
Official site :
https://docs.spring.io/spring-framework/docs/4.3.15.RELEASE/spring-framework-reference/
html/aop.html
https://www.baeldung.com/spring-aop-pointcut-tutorial#:~:text=Pointcut%20Designators,%
2C%20method%20arguments%2C%20or%20annotations.