Monday, 28 September 2015

Secret of Spring AOP.

How AOP works internally ? 

Here we will discuss on logging functionality as one of the AOP usages. Here I have implemented a POC using Java core API to demonstrate similar as Spring AOP functionality.

Prerequisite : Java Core Proxy API, Reflection API and Annotation API (java.lang.reflect, java.lang.annotation  packages)

Secret : Here also the main secrets are proxy object, MethodHandler, reflection and annotation. But the method handler class is main secret player of our discussion, which has the full controller on the proxy objects and when any method call happened on a proxy object it passes through the this handler. Inside the call back method of the handler, using reflection it introspects all the applied annotations and based on that it generates required log statements.


For more about Proxy object/Reflection API/MethodHandler, Please refer to my previous blog
http://secretsinjava.blogspot.in/2015/09/secret-of-spring-jpa-repository.html

Annotation API : Annotations are nothing but meta information about a program element like class, method, variables. Java API having so many built-in annotations but we can define our own custom annotation as well.

In this context using our custom annotations we will enable the logging functionality such that for every method call, based on the applied annotation the log statement will generate. Log statement can be before method call or after method call or on exception.


Source Code :
Annotations: Here We have created some annotations to annotate the method for which we want to generate the log


Worker.java
Here in WorkerController class, WorkerService field is assigned with proxy object, where as in Spring it will be auto wired by Spring Container.
AOPLoggingMethodHandler.java
 
Here in Main class also, WorkerController field is assigned with proxy object, where as in Spring it will be auto wired by Spring Container.
Output:



Thanks you for visiting the page. Please feel free to provide your precious suggestions and comments. 






No comments:

Post a Comment