Understanding of spring aop

Source: Internet
Author: User

1. Problem: You want to add log records, performance monitoring, and security monitoring. 2. initial solution 2.1. disadvantages of the initial solution: Too Many duplicate codes, in addition, it is tightly coupled with 2.2. abstract classes are designed in common, and child classes are individually designed. We will not describe them here, but we will be proud of our shortcomings, solution: decorator mode improved using the decorator mode/Agent Mode: dynamically add some additional responsibilities to an object. As for the added function, the decorator mode is more flexible than generating sub-classes. Proxy mode: provides a proxy for other objects to control access to this object. Disadvantage: tight coupling. Each business logic requires a decorator to implement or proxy 2.4, JDK dynamic proxy solution (more common solution) java code public class MyInvocationHandler implements InvocationHandler {private Object target; public MyInvocationHandler (Object target) implements this.tar get = target;} @ Overridepublic Object invoke (Object proxy, Method method Method, Object [] args) throws Throwable {// 1. record log 2. time Statistics start 3. security check Object retVal = method. invoke (target, args); // 4. return retVal;} public Static Object proxy (Object target) {return Proxy. newProxyInstance (target. getClass (). getClassLoader (), target. getClass (). getInterfaces (), new MyInvocationHandler (target) ;}} [java] public class MyInvocationHandler implements InvocationHandler {private Object target; public MyInvocationHandler (Object target) {this.tar get = target ;} @ Override public Object invoke (Object proxy, Method method, Object [] Args) throws Throwable {// 1. record log 2. time Statistics start 3. security check Object retVal = method. invoke (target, args); // 4. return retVal;} public static Object proxy (Object target) {return Proxy. newProxyInstance (target. getClass (). getClassLoader (), target. getClass (). getInterfaces (), new MyInvocationHandler (target ));}} programming Model Java code // proxy calls the proxy instance of the method on it // method blocking method // Overridepublic Object invoke (Objec T proxy, Method method, Object [] args) throws Throwable {Object retVal = null; // pre-processing // pre-condition determines boolean OK = true; if (! OK) {// does not meet the condition throw new RuntimeException ("You do not have permission");} else {// reflection calls a method retVal = method of the target object. invoke (target, args);} // post-processing return retVal ;} [java] // proxy on which the proxy instance that calls the method // Method to intercept the method // Override public Object invoke (Object proxy, method Method, object [] args) throws Throwable {Object retVal = null; // pre-processing // pre-condition determines boolean OK = true; if (! OK) {// does not meet the condition throw new RuntimeException ("You do not have permission");} else {// reflection calls a method retVal = method of the target object. invoke (target, args);} // post-processing return retVal;} disadvantages: troublesome use, no proxy class, only the CGLIB dynamic proxy solution for proxy interfaces (more common solutions) java code: public class MyInterceptor implements MethodInterceptor {private Object target; public MyInterceptor (Object target) implements this.tar get = target;} @ Overridepublic Object intercept (Object proxy, Method method Method, Object [] args, MethodProxy invocation) throws Throwable {// 1. record log 2. time Statistics start 3. security check Object retVal = invocation. invoke (target, args); // 4. return retVal;} public static Object proxy (Object target) {return Enhancer. create (target. getClass (), new MyInterceptor (target);} [java] public class MyInterceptor implements MethodInterceptor {private Object target; public MyInterceptor (Object target) {this.tar get = target ;} @ Override public Object intercept (Object proxy, Method method, Object [] args, MethodProxy invocation) throws Throwable {// 1. record log 2. time Statistics start 3. security check Object retVal = invocation. invoke (target, args); // 4. return retVal;} public static Object proxy (Object target) {return Enhancer. create (target. getClass (), new MyInterceptor (target);} programming model Java code // parameters intercepted by args in the method proxy instance on which the proxy calls the method/ /Invocation @ Overridepublic Object intercept (Object proxy, Method method, Object [] args, MethodProxy invocation) used to call the Method of the proxy Object) throws Throwable {// pre-processing // pre-condition determines boolean OK = true; if (! OK) {// does not meet the condition throw new RuntimeException ("error");} else {// call a method of the target Object retVal = invocation. invoke (target, args);} // post-processing return retVal ;} [java] // proxy on which the proxy instance that calls the method The args intercepts the parameter // invocation is used to call the @ Override public Object intercept (Object proxy, method method, Object [] args, MethodProxy invocation) throws Throwable {// pre-processing // pre-condition determines boolean OK = true; if (! OK) {// does not meet the condition throw new RuntimeException ("error");} else {// call a method of the target Object retVal = invocation. invoke (target, args);} // post-processing return retVal;} advantages: proxy interface and class disadvantages: troublesome, cannot proxy final dynamic proxy nature: the enhancement to the target object is ultimately manifested as a class (dynamically creating a subclass), depending on whether the manual generation (subclass) or automatic generation (subclass) proxy restrictions: you can only enhance the function before or after the parent class method is called. You cannot modify the function in the middle. To enhance the function in the method call, you must use ASM (java bytecode library) other dynamic proxy frameworks jboss: javassist (javassist by default in hibernate 3.3) (cglib by default before hibernate 3.3) 2.5, AOP solution (general and simple solution) Java code @ Aspectpublic class PayEbiAspect {@ Pointcut (value = "execution (* pay (..)) ") public void pointcut () {}@ Around (value =" pointcut () ") public Object around (ProceedingJoinPoint pjp) throws Throwable {// 1. log // 2. start of time statistics // 3. security check Object retVal = pjp. proceed (); // call the real method of the target object // 4. return retVal;} [java] @ Aspect public class PayEbiAspect {@ Pointcut (value = "execution (* pay (..)) ") public void pointcut () {}@ Aroun D (value = "pointcut ()") public Object around und (ProceedingJoinPoint pjp) throws Throwable {// 1. log // 2. start of time statistics // 3. security check Object retVal = pjp. proceed (); // call the real method of the target object // 4. return retVal;} programming model Java code // 2 Entry Point @ Pointcut (value = "execution (**(..)) ") public void pointcut () {}// 3 interceptor @ Around (value =" pointcut () ") public Object around (ProceedingJoinPoint pjp) of the interceptor) throws Throwable {Object retVal = null ;/ /Pre-processing // pre-condition determines boolean OK = true; if (! OK) {// condition throw new RuntimeException ("You do not have permission");} else {// call a method retVal = pjp of the target object. proceed () ;}// return retVal;} [java] // 2 ing point @ Pointcut (value = "execution (**(..)) ") public void pointcut () {}// 3 interceptor @ Around (value =" pointcut () ") public Object around (ProceedingJoinPoint pjp) of the interceptor) throws Throwable {Object retVal = null; // pre-processing // pre-condition determines boolean OK = true; if (! OK) {// condition throw new RuntimeException ("You do not have permission");} else {// call a method retVal = pjp of the target object. proceed () ;}// post-processing return retVal;} disadvantages: dependent on the AOP framework. Getting Started concept: n focus: you can think of it as something of interest, such as the above payment component; n separation of concerns: refine the problem into a separate part, that is, it can be understood as an inseparable component, such as the above log component and payment component; n cross-cutting focus: it will appear in multiple modules. using existing programming methods, the cross-cutting concerns will be crossed across multiple modules. The result is that the system is difficult to design, understand, implement, and evolve, for example, the log component is cross-sectional with the payment component. Weaving: after the separation of cross-cutting concerns, you need to use a certain technology to integrate the cross-cutting concerns into the system to complete the required functions. Therefore, you need, weaving may take place during the compilation, loading, and runtime. What is nAOP (Aspect Oriented Programming) AOP is a Programming paradigm that provides you to consider the program structure from another perspective to improve Object-Oriented Programming (OOP ). AOP provides a mechanism for developers to describe the cross-concern, and can automatically route the cross-concern to the object-oriented software system, thus realizing the modularization of the Cross-concern. AOP can encapsulate the logic or responsibilities that are unrelated to the business but called by the business module, such as transaction processing, log management, and permission control, this helps reduce system code duplication, reduce coupling between modules, and facilitate future operability and maintainability. What can nAOP do? It is also the benefit of AOP. 1. Reducing the Coupling Degree of modules. 2. Making the system easy to expand. 3. Late binding of design decisions: Using AOP, designers can postpone decision-making for future needs because they can easily implement such requirements as independent aspects. 4: better code reusability: Joinpoint, the basic concept of AOP, indicates the extension point of the Cross-concern to be inserted in the program, the connection points may be class initialization, method execution, method call, field call, or handling exceptions. Spring only supports method execution connection points, which are expressed as "where to do" In AOP "; pointcut: select a set of related connection points, that is, the set of connection points. Spring supports the perl5 Regular Expression and AspectJ start point mode. Spring uses the AspectJ syntax by default, in AOP, it is represented as "where to do the set"; enhancement (Advice): it is also called the behavior of enhancement executed on the connection point, enhancements provide a means to expand existing behaviors at the point selected by the entry point in AOP, including before advice and after advice) around advice, implements AOP in Spring through the proxy mode, and passes the interceptor mode to link the interceptor that wraps the connection points to the enhancement. "What to do"; Aspect/Aspect (Aspect): modularity of the cross-cutting concerns, such as the log component mentioned above. It can be considered as a combination of enhancement, introduction, and entry point. In Spring, Schema and @ AspectJ can be used for organization implementation. In AOP, they are represented as "where to do and what set to do "; target Object: the Object to be woven into the cross-concern, that is, this Object is the Object selected by the starting point and needs to be enhanced, this can also be called an "enhanced object". Because Spring AOP is implemented in the proxy mode, this object is always a proxy object and expressed as "Who to do" In AOP "; AOP Proxy: The AOP framework uses the Proxy mode to create an object, so as to insert an enhancement (application aspect) at the connection point, that is, to apply the aspect to the target object through the Proxy. In Spring, the AOP proxy can be implemented using JDK dynamic proxy or CGLIB proxy, and the Application Section is applied through the interceptor model. Weaving: The process of applying a plane to a target object to create an AOP proxy object, weaving can be performed during compilation, class loading, and runtime. Inter-type declaration: Also known as internal type declaration. Adding additional fields or methods to existing classes allows Spring to introduce new interfaces (which must correspond to an implementation) to all the proxy objects (target objects), they are expressed as "what to do (what to add)" In AOP; Before Advice ): the enhancement is executed before a connection point, but this enhancement cannot prevent the execution before the connection point (unless it throws an exception ). After returning advice: the enhancement that is executed After a connection point is completed normally. For example, a method does not throw any exception and returns a normal result. Post-exception enhancement (After throwing advice): The execution enhancement when the method throws an exception and exits. After (finally) advice: the enhancement executed when a connection point exits (whether it is normal return or abnormal exit ). Surround enhancement: surrounded by an enhancement of a connection point, such as a method call. This is the most powerful enhancement type. Surround enhancement can complete custom behaviors before and after method calls. It will also choose whether to continue executing the connection point or directly return their own return values or throw an exception to end the execution.

Related Article

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.