Aspect Oriented Programming (AOP) allows modularization of crosscutting concerns such as transaction management, Security, Logging etc. In other words, AOP aims at increasing modularity of the application, by separating the crosscutting concerns from the actual business logic implementations. So, cross cutting concern (Logging Aspect) can be modified or removed in future without any change in the Join Point methods, as there is no further need of explicitly adding calls to the cross cutting concern (logging method) from inside the business classes.
Advice methods are never actually invoked by our code. It is by the AOP proxy that gets built around the target advisable object. For example, suppose in our code, I have an EmployeeService that makes a call to some saveEmployee() method of EmployeeDAO class. I want some logging to be done when this saveEmployee() call happens in EmployeeDAO. I have done the AOP configuration properly in the Spring context XML. Now what Spring AOP does internally, is, it will detect for the need to call the Logging Aspect advice method when the method saveEmployee() gets called and when it does feel the need, it builds a proxy called EmployeeDAOProxy around the target EmployeeDAO object as shown below:
Spring AOP implementation uses the existing JDK dynamic proxy to create the Proxy classes with target classes (here, EmployeeDAO) and advice methods (log()) , which are called AOP proxy classes. We can also use CGLIB proxy by adding it as the dependency in the Spring AOP project.
Difference between JDK Proxy and CGLIB proxy
The difference lies in that, JDK dynamic proxy can only proxy if the target class implements any interface, such that all the interfaces implemented by the target class are proxied, whereas CGLIB proxy doesn’t require the target class to implement any interface. It creates proxies by subclassing, where the proxy becomes the subclass of the target class. CGLIB proxying can be forced in a situation where you need to proxy all the methods inside the target class other than those implemented from it’s interfaces.