spring--AOP

AOP:
Overview:
Aspect-oriented programming is a technology that achieves unified maintenance of program functions through pre-compilation and runtime dynamic agents.
Its bottom layer is realized by the way of dynamic proxy.
If the target class is an interface + implementation class, spring uses jdk dynamic proxy. --The prerequisite must have an interface.
If the target class is only an implementation class, spring uses cglib bytecode enhancement.

aop terms:
1.target: The target class, the class that needs to be enhanced. For example: UserService
2.Joinpoint: Join point, a point on the target class that may be enhanced. (Methods on the target class) For example: addUser(), updateUser() ...
3.pointcut: pointcut, the connection point that has been enhanced (method of the target class). For example: addUser()
4.advice: notification/enhancement, notification refers to what to do after intercepting the Joinpoint (method that may be enhanced) of the target class (external method)
5.weaving: weaving, refers to enhancing the advice The process of applying to the target object target to create a new proxy object proxy.
6.proxy: proxy object
7.aspect: aspect, advice and pointcut combination (intercept the external methods that the target class may be enhanced and the target class that has been enhanced method).

JDK dynamic proxy:
Generate dynamic proxy: Integrate notification and target class into one class to generate a proxy class.
Proxy.netProxyInstance(loder,interfaces,h)
             tool class: Proxy.newProxyInstance, this method returns the value Object
 * loader Class loader: loads the dynamic proxy class into the memory.
  * Commonly used: The class loader of the current class A.class.getClassLoader();
  * Class[] interfaces The proxy class needs to implement all interfaces.
  * Method 1: target class.getClass().getInterfaces()
  * Method 2: new Class[]{target class interface.class,...}
 * InvocationHandler interface, processing class, callback function.
  * Each method of the proxy class is executed , will call the invoke method of the processing class
  * Parameter 31: Object proxy, the proxy class itself
  * Parameter 32: Method method, the currently executed method description object
   * Execution target method: method.invoke (target class, actual parameters)
  * parameters 33: Object[] args, the actual parameters of method execution
 Main code: 
  UserService proxyService = (UserService)Proxy.newProxyInstance(
      MyFactory.class.getClassLoader(),
      new Class[]{UserService.class},
      new InvocationHandler(){

       @Override
       public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        
        //1 前通知
        myAspect.before();
        //2 目标方法  , 参考:userService.addUser();
        Object obj = method.invoke(userService, args);
        //3后通知
        myAspect.after();
        
        return obj;
       }});
  
  return proxyService;

CGLIB Proxy:
It is an open source project. It is a powerful, high-performance, high-quality code-generating class library that implements classes and interfaces that can be extended at runtime.
Bytecode enhancement frameworks: cglib, javassist.
Before using cglib, you need to import packages:
a core package, a dependency package:
location: decompress spring-core-3.2.0.RELEASE.jar. Inside cglib and asm
cglib generates proxies:
cglib dynamically generates a subclass of the target class, and the subclass is a proxy class. Requirement: The target class cannot be made final, regardless of the instance of the target class.
   Core class
  Enhancer (enhancement) enhancer = new Enhancer();
   Determine the parent class
  enhancer.setSuperclass(UserServiceImpl.class);
   3.3 Determine the callback function, similar to the jdk invocationHandler
     intercept() method is equivalent to the jdk invoke method
      Parameter 1: proxy, proxy object
      parameter 2: method, the method parameter of the current object
      3: args, the actual parameter
      parameter of the method 4: methodProxy, the proxy of the method
  enhancer.setCallback(new MethodInterceptor(){
   @Override
   public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {   
    //1 notify
    myAspect.before();  
    //2 target method
    Object obj = method.invoke(userService, args);    
    / /3 After notification
    myAspect.after();    
    return obj;
   }
  });
 create proxy class
  UserServiceImpl proxyService = (UserServiceImpl) enhancer.create();  
  return proxyService;

aop alliance notification type:
? The notification type is ultimately used to determine the method name of the method to be executed.
? The AOP Alliance specifies 5 types of notifications: pre-advice, post-advice, surround notification, throwing exception notification, introduction notification (do not study)
 pre-advice org.springframework.aop.MethodBeforeAdvice implements enhanced  post- processing
  before the target method is executed
Advice org.springframework.aop.AfterReturningAdvice
  implements enhanced surround advice after target method execution
 org.aopalliance.intercept.MethodInterceptor[]--The target method must be manually executed
  before and after target method execution to implement enhanced
 exception throwing advice org.springframework.aop. ThrowsAdvice
  implements enhanced introduction advice after method throws exception
 org.springframework.aop.IntroductionInterceptor
  adds some new methods and properties in target class

 

Spring configuration generation proxy--semi-automatically
obtain proxy classes from the spring container

Guide package:
Spring's implementation of aop:
spring-framework-3.2.0.RELEASE\libs-->spring-aop-3.2.0.RELEASE.jar
aop alliance package:
dependency package: spring-framework-3.0.2dependencies\ org.aopalliance\com.springsource.org.aopalliance\1.0.0-->com.springsource.org.aopalliance-1.0.0.jar

Aspect class:
Aspect class (to store notification advice, the aop alliance is required to define the notification type, so that spring can finally determine the method name that needs to be executed)
. MethodInterceptor[]--The target method must be manually executed around the advice: mi. proceed(), this method returns an Object type.

The configuration file creates proxy objects:
mainly through proxy factory beans. That is, the creation of the proxy part of the previous manual proxy is implemented by the spring configuration file.
 <!-- 1 Create target class-->
 <bean id="userServiceId" class="cn.itcast.b_factorybean.UserServiceImpl"></bean>
 <!-- 2 Create aspect class (notification) -->
 <bean id="myAspectId" class="cn.itcast.b_factorybean.MyAspect"></bean>
 <!-- 3 Create a proxy
   ProxyFactoryBean A proxy factory bean that generates another bean, which generates a proxy bean.
  3.1 interfaces, determine the interface
  3.2 target, determine the target class
  3.3 interceptorNames determine the notification
  3.4 optimize Force the use of cglib
  Note: When writing the following attributes and values, use annotations to determine the value type error
 -->
 <bean id="proxyService " class="org.springframework.aop.framework.ProxyFactoryBean">
  <property name="
  <property name="target" ref="userServiceId"></property>
  <property name="interceptorNames" value="myAspectId"></property>
  <property name="optimize" value="true"></property>
 </bean>

 
SpringAOP automatic programming:
Obtain the target class from the spring container and configure it through spring aop programming. If there is configuration, it is actually a proxy class.
An aspectj expression will be used to determine the pointcut.
You need to import the specification package of aspectj in the dependencies (weaving is used here, so the weaving package is imported):
spring-framework-3.0.2dependencies\org.aspectj\com.springsource.org.aspectj.weaver\ 1.6.8.RELEASE-->com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar
The writing of the target class and the aspect class is the same as the semi-automatic one, the main difference is in the configuration file:
configuration:
 <!-- 1 Create a target class -->
 <bean id="userServiceId" class="cn.itcast.c_aop.UserServiceImpl"></bean>
 <!-- 2 Create an aspect class (notification) -->
 <bean id="myAspectId " class="cn.itcast.c_aop.MyAspect"></bean>
 <!-- 3 aop programming
  <aop:config> Perform all aop configuration
  <aop:advisor>


  <aop:pointcut> declares a pointcut, used to describe the target class
    id pointcut name
    expression pointcut expression
     execution (expression syntax) that can match the method
      expression syntax: return value package.class.method (parameter)
       return value :
        String Execution type
        * Any
       package
        cn.itcast Specifies the package
        cn.itcast.. current package, and subpackages
        cn.itcast.crm.*.service.. crm projects, *submodules, services under submodules, and subpackages .
       The class
        UserService specifies the class
        User* User starts with
        *Service ends with Service
        * Any
       method, the same
       parameter as the class
        () No parameter
        (int) One parameter
        (int, int) Two parameters
        (..) Any parameter
      综合:execution(* cn.itcast.crm.*.service..*.*(..))
        -->
 <aop:config>
  <aop:pointcut expression="execution(* cn.itcast.c_aop.*.*(..))" id="myPointcut"/>
  <aop:advisor advice-ref="myAspectId" pointcut-ref="myPointcut"/>
 </aop:config>

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326556260&siteId=291194637