Lesson 8 - Spring AOP
Lesson 8 - Spring AOP
AOP is used in applications that have cross-cutting concerns, that is, pieces of logic or code that are written
in multiple classes/layers as per the requirements.
Common examples:
• Transaction Management
• Logging
• Exception Handling (especially when you may want to have detailed traces or have some plan of
recovering from exceptions)
• Security aspects
• Instrumentation
Understanding Concerns
A concern is a piece of code that performs a specific task. There are two types of concerns:
2) “Cross concerns” are functions that are conceptually separate from the application's business logic
but affect the entire service layer.
Aspect-Oriented Programming provides one way to decouple dynamically core concern from
crosscutting concern.
What Is AOP?
2) The main idea of AOP (Aspect-Oriented Programing) is to isolate the cross-cutting concerns
from the application code, thereby modularizing them as a different entity.
3) Services layer deals with two types of concerns: Core and cross cutting concerns.
Uses of AOP
• Spring AOP provides declarative enterprise services such as declarative transaction management.
• It allow users to implement custom aspects.
• Spring AOP is used to track user activity in large business applications.
• It uses Proxy as a mechanism to implement cross-cutting concerns in a non-intrusive way.
AOP Terminologies
• Aspect: A feature or functionality that cross-cuts over objects. It has a set of APIs (Application
Programming Interface) that provides cross-cutting requirements.
• JoinPoint: It defines the various execution points where an Aspect can be applied
• Pointcut: A Pointcut tells us about the Join Points where Aspects will be applied
• Weaving: It represents a mechanism of associating cross cutting concern to core concern dynamically.
• Proxy: Proxy is an object produced through weaving. There are two types: static proxy and dynamic proxy.
o In static proxy, static method is used to develop and maintain proxy classes for each business method.
o In dynamic proxy, proxy is developed at run time.
• Proxy design pattern: Actual object (business object) is wrapped into another object knows as proxy and
substitutes that object in place of actual object
Pointcut defines where exactly the Advices have to be applied in various Join Points.
Generally, they act as Filters for the application of various Advices into the real implementation.
AOP Terminologies
Pointcut: TYPES
Springs defines two types of Pointcut:
1. Static: It verifies whether the join point has to be advised or not. It does this once the result is catched @reused.
2. Dynamic: It verifies every time as it has to decide the Join Point based on the argument passes to method call.
Pointcut
StaticMethodMatcher DynamicMethodMatcher
Pointcut Pointcut
ControlFlowPointcut
NameMatchMethod AbstractRegexpMethod
Pointcut Pointcut
JdkRegexMethod PerlRegexMethod
Pointcut Pointcut
AOP Terminologies
StaticMethodMatcherPointcut
2. AbstractRegexpMethodPointcut: Besides matching method by name, it can match the method’s name by
using regular expression pointcut.
This pointcut is used to verify join point based on pattern of the method name instead of name.
AOP Terminologies
AbstractRegexpMethodPointcut
This pointcut is used to verify the context from which business method call is made. If method
call is made in specific flow, it will be advice; otherwise, it won’t.
AOP Terminologies
POINTCUT INTERFACE
A Joinpoint is a candidate point in the Program Execution of the application where an aspect can be
plugged in.
This point could be a method being called, an exception being thrown, or even a field being modified.
These are the points where your aspect’s code can be inserted into the normal flow of your application to
add new behavior.
Proxy interrupts the call made by caller to original object. It will have chance to decide whether and
when to pass on the call to original object. In the meantime, any additional code can be executed.
Proxy object
A dynamic proxy class is a class that implements a list of interfaces specified at runtime
so that a method invocation through one of the interfaces on an instance of the class will
be encoded and dispatched to another object through a uniform interface.
AOP Terminologies
Proxy
• In proxy pattern, a class represents functionality of another class. This type of design pattern is a
structural pattern.
• It creates an object that has original object to interface its functionality to outer world. Proxy design
pattern is used when we want to provide controlled access to a functionality.
• It is also used to save on the amount of memory used. Similarly, if you want to control access to an
object, the pattern becomes useful.
Ways to Generate Dynamic Proxy
1. jdk approach: When the business class implements interface, jdk creates proxy for the business object
2. cglib approach: cglib.jar is used when a business class fails to implement any interface, and jdk is
unable to create proxy
AOP Terminologies
Advice
Advice refers to the actual implementation code for an Aspect. Spring supports Method Aspect.
1. Before advice: It executes before a Joinpoint but does not have the ability to prevent execution flow
proceeding to the Joinpoint
3. Around advice: It surrounds a Joinpoint such as a method invocation. It can perform custom behavior
before and after method invocation.
1. To configure these advices, we have to depend on ProxyFactoryBean. This Bean is used to create Proxy
objects for the implementation class along with the Advice implementation.
2. The property ‘proxyInterface’ contains the Interface Name for which the proxy class has to be generated.
3. The ‘interceptorNames’ property takes a list of Advices to be applied to the dynamically generated proxy
class.
• It is used to intercept before the method execution starts. For example, a system may need to perform
some logging operations before allowing users to access resources
• Whenever caller calls the business method, all before advice code is executed prior to the business
method.
• It is used to intercept after the method execution. For example, a system needs to perform some
delete operations after logging out.
invoke()
When an exception happens during the execution of a method, Throws Advice can be used through the
means of org.springframwork.aop.ThrowsAdvice to handle the exception.
• Exception handling code is considered cross cutting code and can be done for entire service layer in
Throwsadvice with different kinds of exception parameters.
Configuring Throws Advice
1. By annotation
2. By XML configuration
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. @Around declares the around advice. It is applied before and after calling the actual method.
4. @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.
5. @AfterThrowing declares the throws advice. It is applied if actual method throws exception.
6. The @Pointcut annotation is used to define the pointcut.
• @Pointcut("execution(public * *(..))") is applied on all the public methods.
• @Pointcut("execution(public Operation.*(..))") is applied on all the public methods of Operation class.
• @Pointcut("execution(* Operation.*(..))") is applied on all the methods of Operation class.
• @Pointcut("execution(public Employee.set*(..))") is applied on all the public setter methods of Employee
class.
• @Pointcut("execution(* Operation.*(..))")
• private void doSomething() {}
• The name of the pointcut expression is doSomething().
7. @Aspect declares the class as aspect
@Before, @After, and @Around will be covered in the scope of this lesson.
@Before
Let’s look at Perform and TrackPerformance classes. Assume that Perform class contains actual business methods.
The AspectJ Before Advice is applied before the actual business logic method USING @Before advice.
@Aspect
public class TrackPerformance{
@Pointcut("execution(* Operation.*(..))")
public void k(){}//pointcut name
TrackPerformance
class @Before("k()")//applying pointcut on before advice
public void myadvice(JoinPoint jp)//it is advice (before advice)
{
System.out.println(“Before advice is called");
}
}
@Before
calling msg...
Before advice is called
msg() method invoked
calling m...
Before advice is called
msgone() method invoked
calling k...
Before advice is called
Msgtwo() method invoked
@After
For @After annotation, use the same Person class and TrackPerformance.
Person class is the same, but @After annotation in TrackPerformance class is used in this case.
@Aspect
public class TrackPerformance{
@Pointcut("execution(* Operation.*(..))")
public void k(){}//pointcut name
TrackPerformance @After("k()")//applying pointcut on before advice
class public void myadvice(JoinPoint jp)//it is advice (before advice)
{
System.out.println(“After advice is called");
}
}
calling msg...
msgone() method invoked
After advice is called
calling m...
msgtwo() method invoked
After advice is called
calling k...
msgthree() method invoked
After advice is called
@Around
@Aspect
public class TrackPerformance
{
@Pointcut("execution(* Operation.*(..))")
public void abcPointcut(){}
@Around("abcPointcut()")
public Object myadvice(ProceedingJoinPoint pjp) throws Throwable
{
System.out.println("Additional Concern Before calling actual method");
Object obj=pjp.proceed();
System.out.println("Additional Concern After calling actual method");
return obj;
}
}
@Around
<aop:config>
<aop:aspect id="myaspect" ref="trackAspect" >
<!-- @Before -->
<aop:pointcut id="pointCutBefore" expression="execution(* Perform.*(..))" />
<aop:before method="myadvice" pointcut-ref="pointCutBefore" />
</aop:aspect>
</aop:config>
</beans>
Advice Aspectj
Spring AOP is best used for application-specific
AspectJ contains friendly design-patterns.
tasks such as security, logging, transactions, etc.
This is proxy-based AOP. You can use method-
This supports all Pointcuts.
execution Pointcut only.
There is less runtime overhead than that of
There can be a little runtime overhead.
Spring AOP.
You need extra build process with AspectJ
It needs Spring jar files only. Compiler or have to setup LTW (load-time
weaving).
Key Takeaways
AOP is used in applications that have cross cutting concerns i.e. a piece of logic
or code that is written in multiple classes/layers as per the requirements.
Spring uses the dynamic proxy approach. A dynamic proxy class is a class that
implements a list of interfaces specified at runtime so that a method invocation
through one of the interfaces on an instance of the class will be encoded and
dispatched to another object through a uniform interface.
Quiz
QUIZ
The Beans in Spring are ________ by default.
1
a. prototype
b. singleton
c. request
d. session
QUIZ
The Beans in Spring are ________ by default.
1
a. prototype
b. singleton
c. request
d. session