Pages

Friday 26 April 2013

Spring AOP

Spring Aspect Oriented Programming is powerful feature of spring

Each application will have some global function/feature to do which applies for all/many/some of the objects depending on the requirement.

To achive such global function/feature spring AOP provides very powerful and effective way.

Basic Terms in AOP

1)Aspect - cross cutting concern ,something global feature of the application.

2)Join Point - point during the execution of the program such as method execution or exception handling code. in simple words the point where the cross cutting concerns can be applied

3)Advice - the Action taken at the join point. means implementation of any global feature/cross cutting feature.

4)Point cut - Expression which matches the exact join points.


Example program

below is the registration program which has the logic for registration.






below is the login program which has the login logic.

 

Now assume i want to have audit details where i want to store each action like register/login etc in some table.
Means basically , iwant to fire insert query to DB on execution of each of the above program.

so what could be done

without AOP, we can call insert query in each of the programs above.
but what if there are 100 such different actions/programs in our applications ?
we need to write insert query in 100 places  or atleast we have to write 100 calls to that insert query


Now we will see how it can be achived very effectively using AOP.

Include following jars in the classpath
1)aspectjrt.jar
2)aspectjweaver.jar
3)cgilib.jar
4)aopalliance.jar
5)asm.jar

add following tag in spring configuration file ie beans.xml in our case
<aop:aspectj-autoproxy/> as follows



create a new service class to add the dependencies and name it has ApplicationService and is as below




Now write our Aspect as follows

 

now see because of the pointcut expression matched to any method inside com.kb package, our audit() method having insert query logic executes automatically without any of the call to this audit() method.

No matter how many methods will be , we can configure using pointcut and wildcard expression and we can make the call automatically without writing in any code in any of the method.

Now run the main program as below


output will be as follows






 Observe that after user registration audit is called and after login also audit aspect is called automatically.

Thanks for Reading.



No comments:

Post a Comment