Spring AOP Series

First, what is AOP
AOP (Aspect-OrientedProgramming, aspect-oriented programming), it can be said to OOP (Object-Oriented Programing, object-oriented programming) added and improved. OOP concepts introduced encapsulation, inheritance, and polymorphism to establish a hierarchy of objects, to simulate a set of behaviors common. When we need to introduce a common behavior for scattered objects, OOP look powerless. In other words, OOP allows you to define the relationship between a top-down, but it does not fit the definition of the relationship from left to right. Such as logging. Log code tends to spread at all levels of the object hierarchy, the core function of the object to which it spread no relation. For other types of code, such as security, exception handling, and continuous transparent as well. Such scattered across unrelated code is called transverse (cross-cutting) code in OOP design, which led to a large number of duplicate code reuse detriment of each module.

AOP technology while on the contrary, it uses a technique called "transverse", the internal cross-sectional decapsulates the object, and those that affect the behavior of the public classes encapsulated into a plurality of reusable modules, and the name for the "aspect", that is respect. The so-called "respect", simply put, is unrelated to those with business, but as a logical or liability business modules together called encapsulated, easy to duplicate code to reduce system and reduce the degree of coupling between modules, and facilitate future may operability and maintainability. AOP is represented by a transverse relationship, if the "subject" is a hollow cylinder, wherein the package is the attributes and behavior of the object; the method aspect-oriented programming, as if a razor, the cross section of these hollow cylinder apart to obtain its message inside. The cut-away section, the so-called "respect" the. Then it won the day with clever work Cherish these cut-away section recovery, leaving no trace.

Use "cross-cutting" technology, AOP the software system is divided into two parts: the core concerns and crosscutting concerns. The main flow of business processes is a core concern, not part of the relationship is with crosscutting concerns. It features a crosscutting concern is that they often occur in many core concerns, and everywhere similar. Such as certification authority, logging, transaction processing. Aop effect separation of concerns is that the various systems, the core and crosscutting concerns separated. As Avanade's senior solutions architect Adam Magee said, AOP is the core idea of ​​"the application business logic with the separation of its support universal service."

AOP implementation technology, divided into two categories: one is dynamic agent technology, the use of the embodiment intercepted message, the message decorated, instead of performing the original object behavior; second static weaving manner, the introduction of a specific syntax to create "aspect", so that the compiler can be woven into the code related to "aspect" during compilation.

Two, AOP scene using
AOP to encapsulate crosscutting concerns, specifically used in the following scenario:
the Authentication permissions
Caching cache
Context passing content delivery
Error handling Error handling
Lazy loading lazy loading
Debugging debug
logging, tracing, profiling and monitoring recording tracks Picture
performance optimization performance optimization
persistence persistence
resource pooling resources pool
synchronization synchronization
transactions Services

Three, AOP concepts

1. connection point (Joinpoint)
      a specific location of the program execution: As before the class begins initialization after the class initialization, before a class method calls, the calls and the like; or a piece of program code in a class has specific properties with boundary points , a specific point in the code becomes "point of attachment", supports only the Spring method of connection points, i.e., only before the method call, method call, and after these points before and after the execution of the method call weaving enhanced. For example: hack the system needs to find a breakthrough, no breakthrough is no way to attack, to some extent, AOP is a hacker, the candidate is the junction point of AOP attack to the target class.

      There are two point of attachment information to determine: a first program execution point is represented by the process; the second point is represented by a relative orientation; as Test.foo () method of the connection point before the execution, the execution point of Test.foo, orientation for the position before the execution method. Spring performed using the tangent point of the positioning point, and the orientation is defined in the enhancement type.

2. The tangent point (Pointcut)
      each program class has many connection points, such as a class has two methods, these methods are two connection points, i.e. the point of attachment is the object classes present in the objective. However, a large number of connection points, how to navigate to a connection point on it? AOP locate specific points by cutting the connection point. By understanding the concept of database queries to the tangent point and the connection point: the point of attachment is equivalent to the records in the database table, and the point of tangency corresponding to the query condition. Connection point and tangent point is not a one to one relationship, a cut point may match a plurality of connection points.

      In Spring, through the tangent point org.springframework.aop.Pointcut interface description, the method and its use as a query-based point of attachment, Spring AOP parsing rules engine is responsible for parsing the query conditions set cut point, find the corresponding the connection point; in fact, precisely, should be executed rather than point connection point, because the connection points including position information of specific program execution point before the method execution, such as after the execution, and cut to a point just positioning method, so if you want to targeting to specific connection points, also you need to provide orientation information.

3. Enhanced (the Advice)
     enhancement is woven into a program code on a target class connection point (like AOP to identity the hacker charged Trojan traffic class), also has enhanced information related to a connection point, which is azimuth execution point. Combined with the implementation of information and orientation point cut point information, we can find the specific connection point, so Spring provides enhanced interfaces are with the azimuth name: BefortAdvice, AfterReturningAdvice, ThrowsAdvice and so on. (Some Advice will be translated into notice, but the notice is to convey a message to the person to be notified and did not do anything for the person to be notified, and the Spring Advice must be embedded into the connection point of a class, and completed the period of additional application logic;)

4. Audience (Target)
     Enhanced woven into the logic of the target class, if there is no AOP, the target business class need to implement all logic, with the help of AOP, the target class implements the program logic that are not only cross-cutting logic, and other monitoring AOP code that can be used dynamically woven into a specific point of attachment.

5. introduce (Introduction)
     introducing a special reinforcement, which add some properties and methods for the class, so that even if the original is not a traffic class implements an interface, by introducing the AOP function, we can add a dynamic class for the service implement logical interface, so that the business class to become the interface implementation class.

6. weaving (Weaving)
weaving process is added to enhance the specific connection point of the target class, the AOP as a loom, the target class, or introduce reinforcing braided together, weaving the AOP three way :
. a weaving during compilation, this requires special java compiler;
. B class loader of weaving, which requires special class loader;
. C dynamic proxy weaving, the operation of the target class to add reinforcing generated way subclass.
Spring dynamic proxy weaving, while the weaving AspectJ using compiler and class loading of weaving.

7. Agent (Proxy)
a class after being woven reinforcing the AOP, to produce a class result, which is a fusion of the original class and Enhanced Logic proxy class.

8. section (Aspect)
cut by the tangent point and the reinforcing composition, including both the transverse logic definitions, including the definition of the point of attachment, Spring AOP is responsible for the implementation of the frame section, it will cross section defined logic woven into the designated section of the connection point.

Summary: AOP's focus is how to enhance applied to the connection point of the target object, where the first two tasks: first, how to cut and enhanced positioning point to a connection point; second, how to write a section in Enhancement code.

Fourth, implement the principle of

1. proxy mode

Agent concept: simply means that, by creating a proxy object to a particular object, we do not refer directly to the original object, but is controlled by the proxy object created a reference to the original object.

Java proxy mode is commonly used design patterns, characterized by his agent with the delegate class class (or object class) has the same interface, the proxy class is responsible for the pre-message delegate class, filtered message, to forward the message to the delegate, and post-processing messages. Usually there is any relationship between the agent class and delegate class, the object of a proxy class is associated with a delegate class of object, the object proxy class itself is not real service, but by the relevant method calls the delegate class of objects to provide specific services.
Acting in accordance with the founding period, the proxy class can be divided into two kinds.
Static Agent: creation or specific tool automatically generates source code, then compile them by the programmer. Before the program is run, the proxy class .class file already exists.
Dynamic Agent: the program is running, use reflection to dynamically create together, without having to manually write code. Dynamic Agent simplifies programming, but also improve the scalability of a software system, because Java reflection mechanism can generate any type of dynamic proxy class.

Proxy Principle: Agent internal object contains a reference to the real object, which can operate real object, while the real object proxy object provides the same interface can substitute for real object at any time. Meanwhile, when the proxy object can perform a real operation objects, other additional operations, corresponding to the real object to be packaged.

The principle of 2.AOP

The key is to achieve AOP AOP proxy AOP framework created automatically. AOP proxy can be divided into two categories:
static proxy: Use the command AOP framework provided by the compiler, so you can generate AOP proxy class at compile time, it is also called enhanced when compiling; Aspectj a static proxy for the representative.
Dynamic Agent: by means of the JDK dynamic proxy at run time, generating AOP CGLIB-like temporary dynamic proxy class in memory, thus enhancing the run time is also called, is the Spring AOP using dynamic proxy.

AOP AOP divided into static and dynamic AOP. Static refers to AOP AspectJ AOP is achieved, he would cut the code is compiled directly into Java class files. Dynamic AOP code section refers to the weaving AOP achieved. Spring's dynamic AOP AOP, to technology: the JDK provide dynamic agent technology  and  CGLIB-(dynamic bytecode enhancement techniques) . Although realization is not the same technology, but they are based on proxy mode is to generate a proxy object.

(1) JDK dynamic proxies

a. JDK is an interface for the dynamic proxy, delegate class and must provide a proxy class interfaces must be implemented, the method only be able to interface agent.
B. JDK dynamic proxy implemented mainly used java.lang.reflect bag InvocationHandler Proxy classes and interfaces.

InvocationHandler Interface:

Take a look at the java API help documentation is how to describe InvocationHandler interface:

InvocationHandler is the interface implemented by the invocation handler of a proxy instance. 

Each proxy instance has an associated invocation handler. When a method is invoked on a proxy instance, the method invocation is encoded and 
dispatched to the invoke method of its invocation handler.

Description: Each dynamic proxy class must implement this interface InvocationHandler, and each instance of the proxy class is associated to a handler, when we call a method through a proxy object when this method calls will be forwarded by InvocationHandler this invoke interface methods to make the call. While the method where we can invoke the method of the proxy object to call to make enhancement processing (such as adding a transaction log, verify permissions and other operations). Let's look at this interface InvocationHandler the only method invoke method:

public interface InvocationHandler { 
     public Object invoke(Object proxy,Method method,Object[] args) throws Throwable; 
}

Parameters:
Object Proxy: refers to the object being proxied.
Method method: the method to call. (Refer to the Method object that we want to call a method of the proxy object)
Object [] args: parameter method call needed. (Refer to it is to accept the real object when a method call parameters)

Subclass InvocationHandler interface may be thought of as a final operation of a proxy class, replace ProxySubject. 

Proxy categories:
Proxy class is designed to complete the operation based agent, may be generated by such implementation class for one or more interfaces dynamically, such a method of operation provides the following:

public static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h) throws IllegalArgumentException 

Parameters:
ClassLoader Loader: class loader
Class [] interfaces <?>: Get all interfaces
subclass instance obtained InvocationHandler interface: InvocationHandler h

JDK dynamic proxy sample:

Definition of a service interface IUserService, as follows:

com.spring.aop Package; 

public interface IUserService { 
    // add the user 
    public void the addUser (); 
    // delete user 
    public void deleteUser (); 
}

A simple implementation class UserServiceImpl, as follows:

com.spring.aop Package; 

public class UserServiceImpl the implements IUserService { 
    
    public void the addUser () { 
        System.out.println ( "add a user!"); 
    } 
    
    public void deleteUser () { 
        System.out.println ( "Delete a user! "); 
    } 
}

Now we have to realize that, before and after, respectively, addUser and deleteUser dynamic implantation process.
JDK dynamic proxy class uses two main java.lang.reflect package: Proxy and InvocationHandler.
InvocationHandler is an interface defined by transverse logic implementing this interface, the calling code and the target class by reflection, dynamic crosscutting and business logic braided together.
Proxy use InvocationHandler dynamically create an instance of a line with an interface to generate proxy object target class.
Below, we create an instance of InvocationHandler DynamicProxy: (when performing a dynamic proxy object in the target method, in fact, will be replaced invoke the method call DynamicProxy)

com.spring.aop Package Penalty for; 

Import java.lang.reflect.InvocationHandler; 
Import java.lang.reflect.Method; 

public class DynamicProxy the implements InvocationHandler { 
    
    // the proxy object (the goal is to give the class to create a proxy object) 
    Private Object target ; 
    
    // transfer agents examples of targets, because the proxy processor needs may be set by other methods. 
    DynamicProxy public (Object target) { 
        this.target = target; 
    } 
    
    / ** 
     * Method of covering java.lang.reflect.InvocationHandler invoke () for weaving (Enhanced) operation. 
     * This method is called to the proxy object, pay attention to is the object inside the method call is the target object, do not be wrong. 
     * Parameters: 
     * Proxy generated proxy object, method is the proxy method, args is a method of receiving a parameter 
     * / 
    public Object Invoke (Object Proxy, Method, Method, Object [] args) {throws the Throwable 
        performed before the target method //
        System.out.println ( "STH do the Before ..."); 
        // call to the target class by reflection method 
        Object result = method.invoke (target, args ); 
        performed after the target method // 
        System.out.println ( "do the After STH ... \ n-"); 
        return Result; 
    } 
}

 Here is the test:

package com.spring.aop; 

created // by java.lang.reflect.Proxy.newProxyInstance () method is invoked dynamically instantiate the proxy instance method 
Import the java.lang.reflect.Proxy; 

public class dynamicTest { 
    
    public static void main (String [] args) { 
        // the agent desired to be certain traffic class 
        IUserService new new target UserServiceImpl = (); 
        // braided target class and the class with transverse 
        DynamicProxy Handler = DynamicProxy new new (target); 
        // create a proxy instance, it can be considered to be the agent adds a certain traffic class crosscutting code (method) of a subclass 
        // Create instance proxy (proxy class is invoked from processing logic and the definition (Handler) to generate a proxy object) 
        IUserService = Proxy (IUserService) the Proxy.newProxyInstance ( 
                target.getClass (). getClassLoader (), the target class // class loader 
                target.getClass (). getInterfaces (), // target class interfaces
                handler); // transverse class  
        proxy.addUser ();
        proxy.deleteUser (); 
    } 
}

Note: The above code to complete the preparation of the code and cross traffic class code and generates a proxy instance, the first parameter is a method newProxyInstance class loader, the second parameter is a set of interfaces implemented by the target class, a first three parameters is the integration of business logic and the logic of cross-woven objects.

Each call to a dynamic proxy instance go through InvocationHandler interface handler when (call processor) to call, without any dynamic proxies perform the operation, but in creating a dynamic proxy, the interface and the associated handler to be achieved, dynamic agency to help tasks to be performed by the agent, to be forwarded to the handler to execute. In fact, call invoke methods. (See is performed when execution agent addUser instance () and deleteUser () method of DynamicProxy invoke () method.)

operation result:

The basic process: create a dynamic proxy Proxy class target class, you need to specify a class of its own object that implements the callback interface when creating InvocationHandler, this class has a callback invoke () method used to intercept calls to the various target class. After a good agent can create calling various methods of the target object directly on the agent.

Dynamic proxy steps:
A. Create a class that implements the interface InvocationHandler, he must implement invoke methods.
B. Create the proxy classes and interfaces.
C. Creating a proxy by the static method newProxyInstance Proxy (ClassLoader loader, Class <?> [] Interfaces, InvocationHandler handler).
D. Through a proxy calling method.

Use JDK dynamic proxies have one big limitation is that it requires that the target class must implement the interface of the corresponding method, it can only create a proxy instance for the interface. We can see in the above test method newProxyInstance Proxy class of the method the second parameter is the target class interface. If the class does not implement the interface, which rely on dynamic cglib agents.

(2) CGLIB dynamic proxy

CGLib with very bottom of the byte code technology, to create a subclass of a class, and the method call interception techniques to intercept all the parent class method in the subclass, and homeopathic implant transverse logic.

Byte code generation technology to achieve AOP, in fact, inheritance is a proxy object, and then Override need to be proxied method, when override this method naturally can insert our own code. Override method because of the need to be the proxy object, so when using AOP to achieve natural CGLIB technology, it must be proxied request requires methods can not be final method, because the final method can not be overridden by subclasses.

a. CGLIB using dynamic proxies are not required to have an interface, the generated object is a proxy object is a subclass of the target object, it is necessary to process the proxy is private or not the final or static.
b. Using dynamic proxy CGLIB cglib need to rely on a jar (asm.jar introduction and cglib-nodep-2.1_3.jar)

CGLibProxy and JDKProxy proxy mechanism essentially similar, but its dynamic proxy proxy object does not implement an interface, but the target class extends the subclass. In other words JDKProxy returns dynamic proxy class, to achieve another version of the target class implements the interface, which implements a proxy (as UserDAOProxy UserDAOImp relationship with) the target class, and returns CGLibProxy dynamic proxy class, the target agent is a subclass of class (proxy class extends the UserDaoImpl class)

cglib proxy Features:
CGLIB is for the class to implement the agency, its principle is to generate a subclass of the specified target class and method in which the cover. Because the use of inheritance, it can not finall classes inherit .

We use the example CGLIB achieve the above:

The final proxy operation classes:

com.spring.aop Package; 

Import the java.lang.reflect.Method; 

Import the net.sf.cglib.proxy.Enhancer; 
Import net.sf.cglib.proxy.MethodInterceptor; 
Import net.sf.cglib.proxy.MethodProxy; 

public CglibProxy the implements MethodInterceptor {class 
    
    // enhancer, dynamic code generator 
    enhancer enhancer enhancer new new = (); 
    
    / ** 
     * Create a proxy object 
     * @param clazz 
     * @return returns proxy object 
     * / 
    public Object The getProxy (class clazz) { 
        / / set the parent class, which is proxied class (target class) 
        enhancer.setSuperclass (clazz); 
        // set a callback (when calling the parent class method, the callback this.intercept ()) 
        enhancer.setCallback (the this); 
        // dynamically created instance of a subclass (UserServiceImpl class extends the dynamic) technology bytecode 
        return Enhancer .create (); 
    }
    
    / ** 
     * Interception: intercepting and processing of invoking the target method in the proxy instance, returns the result 
     * obj: a target object proxy instance; 
     * method: method call target object instance of the parent class method; 
     * args: call the parent class method passing parameters; 
     * proxy: a proxy method to call the target method 
     * / 
    public Object Intercept (Object obj, method, method, Object [] args, MethodProxy proxy) 
        throws the Throwable { 
        
        System.out.println ( "------- - the meaning of four test parameters intercept method ----------- "); 
        System.out.println (" obj: "+ obj.getClass ()); 
        System.out.println (" method : "+ method.getName ()); 
        System.out.println (" Proxy: "+ proxy.getSuperName ()); 
        ! IF (args = null && args.length> 0) {
        } 
            for (Object value: args) {
                System.out.println ( "args:" + value); 
            } 

        // performed before the target method 
        System.out.println ( "STH do the Before ..."); 
        // call the target method 
        // call the parent class instance proxy method in class, that is to call the target business class method 
        Object result = proxy.invokeSuper (obj, args ); 
        performed after the target method // 
        System.out.println ( "STH do the after ... \ the n-"); 
        return the Result ; 
    } 
}

Test categories:

com.spring.aop Package; 

public class CglibProxyTest { 
    
    public static void main (String [] args) { 
        CglibProxy new new CglibProxy Proxy = (); 
        // certain traffic classes dynamically generated by the java.lang.reflect.Proxy The getProxy () of subclasses, i.e. proxy class, and then to obtain a proxy instance 
        // create proxy class dynamically generated by the subclass manner 
        IUserService target = (IUserService) proxy.getProxy (UserServiceImpl.class); 
        target.addUser (); 
        target.deleteUser (); 
    } 
}

The basic process: the need to write your own proxy class that implements the interface MethodInterceptor, there is a intercept () callback method used to intercept calls to the target method, which use methodProxy to call the target method. Create a proxy object to use Enhance class, use it to set the target class good proxy, the proxy class instance by the intercept () callback, and finally create and return a proxy instance with the create ().

Output:

We have seen achieved the same effect. Its principle is to generate a parent enhancer.setSuperclass (clazz) subclass enhancer.create (), then the parent class intercept enhancer.setCallback (this). Method for covering the parent class, the superclass method It can not be final.

Summary:
  (1) It can be seen by the output of a final call com.spring.aop.UserServiceImpl subclass (also proxy class) Method of com.spring.aop.UserServiceImpl $$ EnhancerByCGLIB $$ 43831205.
  (2). Private, final and static methods can not be modified agent.

Note:
  (. 1) .CGLIB agent is achieved by implementing a subclass of the target class, you need to define the interface.
  (2) Generate a proxy object is most used to generate a proxy object MethodInterceptor Interface Callback interface Enhancer and inherited, set the callback object's role when calling the proxy object methods to deal with will give callback object.
  (3) Create subclass object is to create a proxy object by using the object class Enhancer, by providing enhancer.setSuperClass (Class class) and enhancer.setCallback (Callback callback).

Interpretation intercept method MethodInterceptor interface:

Object intercept(Object var1, Method var2, Object[] var3, MethodProxy var4) throws Throwable;

Parameters: Object var1 representative of the proxy object is a subclass, Method var2 reflecting object represents the method to be called, the third parameter is a parameter passed to the called method, InvocationHandler Invoke interface method of the first three parameters and the JDK meaning of the parameters are the same, the object is a fourth parameter MethodProxy cglib generating method used in place of the object, this object is higher than the efficiency of the method object jdk.

If you use an object method to invoke the target object's method: method.invoke (var1, var3), it will be stuck in an infinite recursive loop, because the target object is a sub-agent class object target class.

MethodProxy invoke class provides two methods:

public Object invokeSuper(Object obj, Object[] args) throws Throwable;
public Object invoke(Object obj, Object[] args) throws Throwable;

Note at this time should use invokeSuper () method, as the name suggests is called the parent class, if using invoke method, you need to provide a target class object, but we only target class subclass proxy object, it will be stuck in an infinite recursive loop.

CGLIB performance dynamic proxy objects created much higher than the performance of the JDK dynamic proxy object created, but to create a JDK dynamic proxy objects than to create a dynamic proxy object takes longer.

JDK agents and agents CGLIB summary (the premise of generating a proxy object is cut AOP)
(1), if the target object implements the interface, default JDK implementation using dynamic proxy AOP case. If an object is simply generated with the IOC, there is no cut into the AOP will not generate the proxy, only a NEW instance, to the Spring Bean Factory.
(2), if the target object implements the interface, you can force CGLIB AOP implementation
how to force CGLIB achieve AOP
* Add CGLIB library
* is added in the spring configuration file <aop: aspectj-autoproxy proxy- target-class = "true" / > can be forced to use
(3), if the target object does not implement the interface must CGLIB library, spring is automatically converted (not implemented on the interface between the agent used CGLIB JDK dynamic proxy and CGLIB, the type of interface used to with JDK dynamic proxies)

JDK dynamic proxy CGLIB bytecode and generating difference:
(. 1), a JDK dynamic proxy only for the classes that implement the interface generation agent, and not for the class. CGLIB agent is achieved for the class, the main class is specified to generate a sub-class, wherein the method of covering. Because it is inherited, so the class or method is best not to be declared as final.
(2), a JDK agent need not rely on third-party libraries, can be carried out as long as a JDK agent, it has several requirements
* realization of InvocationHandler;
* used to generate the proxy object Proxy.newProxyInstance;
* the proxy object must implement the interface ;
CGLib CGLib library must rely on, but it needs to implement any interface proxy class is specified to generate a subclass of the class, wherein the method of covering, an inherited.
(3), is to achieve a core jdk InvocationHandler interface using invoke () method for the processing section, call the corresponding notification. The core is to achieve cglib MethodInterceptor interface using Intercept () method of aspect-oriented processing, call the corresponding notification.

V. Summary

     AOP is widely used to deal with some system-level services with a cross-section properties, AOP is a good complement to the emergence of OOP, which allows developers to use a more elegant way to deal with a cross-cutting nature of the service. Either AOP implementation, whether AspectJ, or Spring AOP, they need to generate a dynamic AOP proxy class, the difference is only to generate different timing AOP proxy class: AOP proxy class generated when using AspectJ compiler, so it has a better performance, but it requires the use of specific compiler for processing; Spring AOP and AOP proxy class is used to generate run time, processing without using a specific compiler. Because Spring AOP AOP proxy needs to be generated on each run, so performance is slightly worse.

Guess you like

Origin www.cnblogs.com/yunianzeng/p/11601075.html