Spring AOP Implementation Principles

Source: Internet
Author: User

What is AOPAOP (aspect-orientedprogramming, aspect-oriented programming), can be said to be the complement and refinement of OOP (object-oriented programing, object-oriented programming). OOP introduces concepts such as encapsulation, inheritance, and polymorphism to create an object hierarchy that simulates a collection of public behavior. When we need to introduce public behavior to scattered objects, oop seems powerless. In other words, OOP allows you to define relationships from top to bottom, but it is not appropriate to define left-to-right relationships. such as logging capabilities. Log code is often spread horizontally across all object hierarchies, and has nothing to do with the core functionality of the objects it spreads to. This is true for other types of code, such as security, exception handling, and transparent persistence. This irrelevant code scattered around is called crosscutting (cross-cutting) code, and in OOP design, it leads to a lot of duplication of code, rather than the reuse of individual modules.    encapsulates the logic or responsibility that is not related to the business but is invoked by the business modules, which facilitates the reduction of repetitive code, reduces the coupling between modules, and facilitates future operability and maintainability. One feature of   crosscutting concerns is that they often occur in a number of core areas of concern and are essentially similar across the site. such as permission authentication, logging, transaction processing. The core idea of &NBSP;AOP is to "decouple the business logic in the application from the generic services that support it." &NBSP;AOP uses scenario AOP to encapsulate crosscutting concerns, which can be used in the following scenarios:  authentication permissions Caching Cache context passing content delivery error handling fault handling lazy Loading lazy load Debugging debug logging, tracing, profiling and monitoring record tracking optimization calibration performance Optimization performance optimization persistence persistence Resource pooling resource pool synchronization synchronous transactions transaction implementation of AOP technology is divided into two major categories: first, the use of dynamic Agent technology, the use of interception of messages, the message is decorated to replace the original object behavior of the execution The second is to use static weaving in a way that introduces a specific syntax to create "facets" that allow the compiler to weave code about "aspects" during compilation.   How to use spring AOP can use Spring AOP in a configuration file or programmatically. Configuration can be done through an XML file to, there are about four ways: 1.         Configure Proxyfactorybean, explicitly set advisors, advice, target, etc. 2.         Configure Autoproxycreator, in this way, using the defined bean as before, but what you get from the container is already a proxy object 3.         Configure 4 with <aop:config>.         Configure with <aop:aspectj-autoproxy>, use ASPECTJ annotations to identify notifications and pointcuts   You can also use Spring AOP in a programmatic way using proxyfactory, and Proxyfactory provides a way to set the target object, advisor and other related configurations, and finally get the proxy object through the GetProxy () method  spring the generation of AOP proxy objects Spring provides two ways to generate proxy objects: Jdkproxy and Cglib, which are generated by aopproxyfactory depending on the configuration of the Advisedsupport object. The default policy is to use the JDK dynamic Agent technology if the target class is an interface, otherwise use Cglib to generate the proxy.   Specific generated code in Jdkdynamicaopproxy this class   gets the interface to be implemented by the proxy class, in addition to the advised object configured, will also add Springproxy, advised (Opaque=false)   Check the interface above to get an interface that defines equals or hashcode   calls Proxy.newproxyinstance to create proxy objects      public Object GetProxy (ClassLoader ClassLoader) {        if (logger.isdebugenabled ()) {   & nbsp        logger.debug ("Creating JDK dynamic ProXY:target source is "+this.advised.gettargetsource ());         }         class[] Proxiedinterfaces = Aopproxyutils.completeproxiedinterfaces (this.advised);         finddefinedequalsandhashcodemethods (proxiedinterfaces);         return proxy.newproxyinstance (ClassLoader, proxiedinterfaces, this);  }  invocationhandler is a method invocation of a proxy object generated by the core of the JDK dynamic agent is delegated to the Invocationhandler.invoke () method.
  1. public Object invoke(Object proxy,Method method,Object[] args) throwsThrowable {
  2. MethodInvocation invocation =null;
  3. Object oldProxy =null;
  4. boolean setProxyContext =false;
  5. TargetSource targetSource =this.advised.targetSource;
  6. Class targetClass =null;
  7. Object target =null;
  8. try{
  9. //eqauls()方法,具目标对象未实现此方法
  10. if(!this.equalsDefined &&AopUtils.isEqualsMethod(method)){
  11. return(equals(args[0])?Boolean.TRUE :Boolean.FALSE);
  12. }
  13. //hashCode()方法,具目标对象未实现此方法
  14. if(!this.hashCodeDefined &&AopUtils.isHashCodeMethod(method)){
  15. return newInteger(hashCode());
  16. }
  17. //Advised接口或者其父接口中定义的方法,直接反射调用,不应用通知
  18. if(!this.advised.opaque &&method.getDeclaringClass().isInterface()
  19. &&method.getDeclaringClass().isAssignableFrom(Advised.class)){
  20. // Service invocations onProxyConfig with the proxy config...
  21. returnAopUtils.invokeJoinpointUsingReflection(this.advised,method, args);
  22. }
  23. Object retVal =null;
  24. if(this.advised.exposeProxy){
  25. // Make invocation available ifnecessary.
  26. oldProxy =AopContext.setCurrentProxy(proxy);
  27. setProxyContext =true;
  28. }
  29. //获得目标对象的类
  30. target = targetSource.getTarget();
  31. if(target !=null){
  32. targetClass = target.getClass();
  33. }
  34. //获取可以应用到此方法上的Interceptor列表
  35. List chain =this.advised.getInterceptorsAndDynamicInterceptionAdvice(method,targetClass);
  36. //如果没有可以应用到此方法的通知(Interceptor),此直接反射调用 method.invoke(target, args)
  37. if(chain.isEmpty()){
  38. retVal =AopUtils.invokeJoinpointUsingReflection(target,method, args);
  39. }else{
  40. //创建MethodInvocation
  41. invocation = newReflectiveMethodInvocation(proxy, target, method, args, targetClass, chain);
  42. retVal = invocation.proceed();
  43. }
  44. // Massage return value if necessary.
  45. if(retVal !=null&& retVal == target &&method.getReturnType().isInstance(proxy)
  46. &&!RawTargetAccess.class.isAssignableFrom(method.getDeclaringClass())){
  47. // Special case: it returned"this" and the return type of the method
  48. // is type-compatible. Notethat we can‘t help if the target sets
  49. // a reference to itself inanother returned object.
  50. retVal = proxy;
  51. }
  52. return retVal;
  53. }finally{
  54. if(target !=null&&!targetSource.isStatic()){
  55. // Must have come fromTargetSource.
  56. targetSource.releaseTarget(target);
  57. }
  58. if(setProxyContext){
  59. // Restore old proxy.
  60. AopContext.setCurrentProxy(oldProxy);
  61. }
  62. }
  63. }
The main process can be described as: Get a chain of notifications that can be applied to this method (Interceptor Chain), apply notifications if there is one, and execute joinpoint; If not, the direct reflection executes the joinpoint. And the key here is How the notification chain is obtained and how it is executed。 Reference article Spring AOP implementation principle: http://blog.csdn.net/moreevan/article/details/11977115

Spring AOP Implementation Principles

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.