Nearby lessons
15 of 35Spring - AOP (Aspect Oriented Programming)
- Understand Spring - AOP (Aspect Oriented Programming)
- See working code examples
- Learn from common mistakes and Q&A
Learn Spring - AOP (Aspect Oriented Programming) step by step — simple explanations, complete programs with their output, common beginner mistakes, and exam-style MCQs.
Aspect Orientation
In general, in enterprise applications development, if we use Object Oriented Programming languages then we have to provide the implementation by combining both Applications business logic and services logic.
Aspect Orientation
If we use the above style of implementation then we are able to get the following problems.
- It is very difficult to modify the services logic, it required to modify in all business method.
- It will not provide Sharability
- It will not provide Code Reusability.
- It will provide tightly coupled design.
To overcome the above problems we have to use Aspect Orientation. Aspect Orientation is not a programming language, it is a methodology or a paradiagm, it will be applied on Object Oriented Programming in order to get loosely coupled design and in order to improve sharability and Reusability. The basic idea behind Aspect Orientation is to separate all services logic from System Business logic , declaring each and every service as an aspect and injecting these aspects into the application Business logic in the respective locations by using Dependence Injection.
In enterprise Applications, AOP will provide the following advantages.
- In Enterprise applications, Business components looks very clean and having only business implementation statements.
- All Services are implemented in a common place which simplifies code maintenance.
- We can make changes in common location , so that, the changes are reflected to all business methods.
AOP is implemented by the following vendors.
- AspectJ
- Spring AOP
- JBOSS AOP
Spring Framework is providing the following two types of implementations
- Schema Based Implementation
- AspectJ
- Declarative Based Approach
- Annotation Based Approach
AOP Terminology
In general, AOP will use the following terminologies inorder to implement AOP based implementation.
- Aspect
- Advice
- Join point
- Pointcut
- Target
- Proxy
- Weaving
- Introduction
Aspect
An Aspect is the concern or a service which we want to implement in the application such as logging, transactional , Security etc.
Advice
An Advice is the actual implementation of the aspect. Aspect is a concept and Advice is the concrete implementation of the concept.
Join point
A JoinPoint is a point in the execution of the program where an aspect can be applied. It could be before/after executing the method, before throwing an exception, before/after modifying an instance variable etc.
Pointcut
PointCuts tell on which join points the aspect will be applied. An advice is associated with a point cut expression and is applied to a join point which matches the point cut expression.
Target
Target is a business component class which is being advised
Proxy
Proxy is the object which is created by the framework after applying the advice on the target object. Proxy = target + advice(s)
Weaving
Weaving is the process of applying the aspect on the target object to product the proxy object. Weaving can be done at compile time, class loading time or runtime. Spring AOP supports weaving at runtime.
Introduction
An Introduction allows adding new methods or attributes to existing classes. The new method and instance variable can be introduced to existing classes without having to change them, giving them new state and behavior. Advices In Spring
Advices In Spring
Advice is the implementation of Aspect. An Advice provides the code for implementation of the service or Aspect. As an example consider logging service, logging is an Aspect and Advice denotes the implementation of Log4j.
In general, all the advices code will not be included in business methods at compile time, these services will be included at runtime.
Spring Framework is providing the following various advices.
- Before Advice
- After Advice
- After-Returning
- After-throwing
- Around Advice
Before Advice
Before advice contains service/Aspect implementation , it will be executed before executing the respective business method.
To represent Before Advice, Spring Framework has provided a predefined interface in the form of "org.springframework.aop.MethodBeforeAdvice".
If we want to use Before Advice in Spring applications , first, we have to declare an user defined class, it must implement org.springframework.aop.MethodBeforeAdvice interface and we must provide implementation for the following method provided by MethodBeforeAdvice interface.
public void before(Method m,Object[] Bus_Meth_Params, Object target)throws Exception
Where java.lang.reflect.Method parameter is able to provide metadata of the Business method to which BeforeAdvice is applied.
Where Object[] is providing business method parameter values in the form of Objects. Where Object is representiung the target Object.
Note: The services which are implemented in before() method are executed at before executing business logic.
After Advice[After Returning Advice]
It is same as Before Advice, But this advice contains services which are applied after completion of our business method logic To create an after returning advice in spring, we have to declare an user defined class, it must implement org.springframework.aop.AfterReturningAdvice and we must implement the following method.
public void afterReturning(Object returnValue,Object[] args, Object target)throws Exception
Where first parameter is representning return value in the form of Object type. Where second parameter is able to represent business method parameters in the form of
Object[]. Where third parameter is representing Target Object.
After Advice[After Returning Advice]
Note: In Schema Based implementation, After Advice and After-Returning Advice are same, but, in Annotation approach both are different.
After-throwing or Throws Advice
This advice will be executed after throwing an exception from the business method.
To represent After-Throwing Advice, Spring Framework has provided a predefined interface in the form of "org.springframework.aop.ThrowsAdvice".
If we want to use After Throwing Advice in Spring applications , first, we have to declare an user defined class, it must implement org.springframework.aop.ThrowsAdvice interface and we must provide implementation for the following method provided by ThrowsAdvice interface. public void afterThrowing([Method, args, target], ThrowableSubclass)
Some Examples of the above form are public void afterThrowing(Exception ex) public void afterThrowing(RemoteException) public void afterThrowing(Method method, Object[] args, Object target, Exception ex) public void afterThrowing(Method method, Object[] args, Object target, ServletException ex)
Where java.lang.reflect.Method parameter is able to provide metadata of the Business method to which BeforeAdvice is applied.
Where Object[] is providing business method parameter values in the form of Objects. Where Object is representiung the target Object. Where Exception is representing the generated Exception.
Around Advice
Around Advice will be executed before and after executing the business method. Around Advice is combination of both Before and After Advice. Around Advice is not given by spring framework and it is from Open Source implementation called AOP alliance. Around Advice can be used by any framework which supports AOP.
To represent Around Advice, Spring AOP Aliance has provided a predefined interface in the form of org.aopalliance.intercept.MethodInterceptor.
MethodINterceptor has provided the following method inorder to provide services before and after execution of the business method.
public Object invoke(MethodInvocation mi)throws Throwable
In Around Advice, we will implement Before and After Advice in invoke() method, in invoke() method will provide before advice logic before calling proceed() method and we will provide After Advice logic after calling proceed() method.
Note: Around Advice can access the return value of business method and it can modify the value and it can return a different value back to the client, as return type is Object, but in the After Advice its not possible right, as its return type is void.
PointCut
PointCut defines at what Joinpoints Advices has to be applied, instead of defining advices at all join points.
If we want to use PointCuts in AOP based applications then we have to configure that pointcuts in Spring configuration File.
To configure Pointcuts in configuration file then we have to use the following two types of PointCuts.
- Static Pointcut
- Dynamic Pointcut
Static Pointcut
Static pointcuts define advice that is always executed. Static pointcuts are based on method and target class, and cannot take into account the method's arguments. Static pointcuts are sufficient - and best - for most usages. It's possible for Spring to evaluate a static pointcut only once, when a method is first invoked: after that, there is no need to evaluate the pointcut again with each method invocation.
To represent Pointcuts , Spring framework has provided a predefined interface in the form of "org.springframework.aop.PointCut". SpringFramework has provided the following Implementation classes for org.springframework.aop.PointCut interface.
- NameMatchMethodPointcut
- Perl5RegexpMethodPointcut
- JdkRegexpMethodPointcut
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 then we have to configure Pointcut and Advisor in apring configuration file.
In spring applications, we will use "DefaultPointCutAdvosor" inorder to suggest the advices to the Pointcuts.
Where if we want to use NameMatchMethodPointcut then we have to use "mappedNames" property of type "array" and we must provide business method names as values to which we want to apply advices.
Dynamic Pointcut
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.
Dynamic Pointcut
Where if we want to use DefaultPointcutAdvisor in spring applications then we have to use "pointcut" and "advice" properties.
Example On Before Advice — Employee.java
Example On Before Advice — EmployeeService.java
Example On Before Advice — EmployeeServiceImpl.java
Example On Before Advice — EmployeeValidator.java
Example On Before Advice — ApplicationContext.java
Example On Before Advice — Test.java
Example On After Advice — Student.java
Example On After Advice — InstituteService.java
Example On After Advice — InstituteServiceImpl.java
Example On After Advice — ThanqAdvice.java
Example On After Advice — ApplicationContext.java
Example On After Advice — Test.java
Example On Throws Advice — Movie.java
Example On Throws Advice — MovieService.java
Example On Throws Advice — MovieServiceImpl.java
Example On Throws Advice — MoneyReturnAdvice.java
Example On Throws Advice — ApplicationContext.java
Example On Throws Advice — Test.java
Example on Around Advice — Account.java
Example on Around Advice — Cheque.java
Example on Around Advice — TransactionService.java
Example on Around Advice — TransactionServiceImpl.java
Example on Around Advice — ChequeClearenceAdvice.java
Example on Around Advice — applicationContext.java
Example on Around Advice — Test.java
AspectJ
AspectJ is well known in AOP language, it provides specialized syntax to express concerns. It also provides tools to add a concern into the system and enables crosscutting concern and modularization, such as logging, error checking and handling, and so on.
Spring is supporting AspectJ in the following two ways.
- Declarative approach
- @AspectJ annotation style approach
Declarative approach — applicationContext.xml
IN declarative approach, we will use Aspectj Namespace tags inorder to declare aspects, advices, Pointcuts,......
In declarative configuration approach, all the aspect declarations are placed under the <aop:config/> tag.
To use AOP namespace tags, we need to import the spring-aop schema.
Declarative approach
- <aop:config>
- <!-- contains aspect configuration and all method related configuration -->
- </aop:config>
- </beans>
Note:The aop:config will contain all aspect configurations and all specific method-related configurations, such as around, pointcut, and so on.
Declaring Aspects
To declare aspects by using AspectJ namespace tags we have to use the following tags.
<aop:config> <aop:aspect id="--" ref="--"> -----
</aop:aspect> <aop:config>
Where "id" attribute will take Aspect id value. Where "ref" attribute will take identity of the class ehich has declared in the configuration
file by using <bean> tag in out side of <aop:aspect> tag.
Declaring Pointcuts
A pointcut helps in determining the join points to be executed with different advices. To declare pointcuts we have to use the following tags in configuration file.
<aop:config> <aop:aspect id="----" ref="----"> <aop:pointcut id="----" expression="------"/>
</aop:aspect>
</aop:config>
Where "id" attribute in <aop:pointcut> tag will take identity to the Pointcut. Where "expression" attribute in <aop:pointcut> will take AspectJ expression to define
expression for the business methods which are required Advices. Where "expression" attribute will take "execution" function with an expression.
EX:
<aop:pointcut id="businessService" expression="execution(* com.durgasoft.service.*.*(..))"/> In the above code, expression will repersent all java methods with any type of return type.
Examples on Pointcut Expressions
- execution (* com.durgasoft.service.EmployeeService.*(..))
The above Expression matches all of the methods declared in the EmployeeService interface The above expression 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(* EmployeeService.*(..))
The above Expression matches all methods of EmployeeService interface which are existed in the present package with any type of access modifier and with any return type.
- execution(public * EmployeeService.*(..))
The above Expression matches all public methods of EmployeService interface with any return type.
- execution(public Employee EmployeeService.*(..))
The above Expression matches all public methods of EmployeeService interface with Employee return type.
- execution(public Employee EmployeeService.*(Employee, ..))
The above Expression matches all methods of EmployeeService interface with Employee return type and first parameter as Employee.
- execution(public Employee EmployeeService.*(Employee, Integer))
The above Expression matches all public methods of EmployeeService with Employee return type and with Employee as First parameter and Integer type parameter as second.
Declaring Advices
Spring AspectJ is supporting thye following five advices .
- <aop:before> It is applied before calling the actual business logic method.
- <aop:after> It is applied after calling the actual business logic method.
- <aop:after-returning> it is applied after calling the actual business logic method. It can be
used to intercept the return value in advice.
- <aop:around> It is applied before and after calling the actual business logic method.
- <aop:after-throwing> It is applied if actual business logic method throws exception.
All the above advices tags contains "method" and "pointcut-ref" attributes, where "method" atribute will take advice method and "pointcut-ref" attribute will take Pointcut reference whic we declared in Configuration file.
Declaring Advices — Employee.java
Steps to prepare Application by using AspectJ namespace tags
- Declare Beans.
- Declare Service interface
- Declare Service interface implementation class.
- Create Aspect class
- Prepare Spring Configuration file.
- Prepare Test Application
Example On AOP namespace tags
Declaring Advices — EmployeeService.java
Declaring Advices — EmployeeServiceImpl.java
Declaring Advices — LoggingAspectBean.java
Declaring Advices — applicationContext.xml
Declaring Advices — Test.java
Declaring Advices — Show.java
Example:
Declaring Advices — ShowService.java
Declaring Advices — ShowAspect.java
Declaring Advices — applicationContext.xml
Declaring Advices — Test.java
@AspectJ annotation style approach
Spring Framework supporting Annotations to support AspectJ implementation in the form of "org.aspectj.lang.annotation" package.
Spring AspectJ AOP implementation provides the following annotations — Account.java
- @Aspect: It will declare a class as an aspect. actual
- @Pointcut: It will declare a pointcut expression.
- @Before: It will declare before advice, It will be executed before executing the
Business method.
- @After: It will declare after advice, It will be executed after executing the actual Business
method and before returning result.
- @AfterReturning: It declares after returning advice, It will be executed after calling the
actual Business method and after returning result.
- @Around: It declares around advice, It will be executed before and after calling the actual
Business method.
- @AfterThrowing: It declares the throws advice, It will be executed if the actual Business
method throws exception.
Note: To activate all the above annotations in Spring applications we have to use <aop:aspectj- autoproxy/> tag in spring configuration file.
Example:
Spring AspectJ AOP implementation provides the following annotations — TransactionService.java
Spring AspectJ AOP implementation provides the following annotations — TransactionServiceImpl.java
Spring AspectJ AOP implementation provides the following annotations — InsufficientFundsException.java
Spring AspectJ AOP implementation provides the following annotations — TransactionAspect.java
Spring AspectJ AOP implementation provides the following annotations — applicationContext.xml
Spring AspectJ AOP implementation provides the following annotations — Test.java
- Key ideas of Spring - AOP (Aspect Oriented Programming) explained simply
- Ready-to-use code examples
- Exam-style questions at the end