Thursday, October 25, 2018

Spring AOP with example

What is AOP ?

"AOP(Aspect Oriented Programming)  is programming way, that helps to increase modularity and avoids strong coupling of code by separating cross-cutting concerns". It is one of the key components of Spring Framework.
Cross-cutting concern is a code logic which is scattered throughout the application and it affects entire application. Transaction management and logging are best examples of cross cutting concerns. 
"The key unit of modularity in OOP is class, whereas aspect is the unit of modularity in AOP "

Why AOP is needed?

Sometime, while coding we add some logic and it gets scattered and tangled through out the application. Let's say, we want to add code to check time performance of each method  of services from package . Without AOP, we supposed add few lines of code at each and every expected method. But using AOP we can put above logic at one place and call it whenever required instead of duplicating and scattering it all over project.

AOP Concepts :

1. Aspect : A modularization of a concern that cuts across multiple classes. e.g Transaction management.
2. Join-Point : A point during execution of program, such as execution of method or handling of an Exception. In spring AOP , join-point always represents method execution.
3. Advice : Action taken by an aspect at particular join point.
4. Pointcut : Predicate that matches join point.
5. Target Object : Target to which aspect applies. 

How to Implement AOP ?

Ways to implement AOP : 
1. By Spring 1.2 - dtd based style (old style) 
2. By ApectJ annotation-style 
3. Spring XML Configuration Style

Example (Spring XML configuration style)

Logging aspect implementation for target service with spring xml based configuration.

Step 1 : Create maven project as below.



Step 2 : Add required maven dependencies :


Step 3: Write Target class/service to which we want to apply aspect




Step 4 : Write Aspect as below.




Step 5 : Create applicationContext.xml file for adding aspect and bean configurations as below.




Step 6 : Write Application.java class for executing example. This is main class just for execution.




After execution of  Application.java, we get output as below.



Above example can be found on Github projects.


No comments:

Post a Comment