Spring Aop Detailed

Source: Internet
Author: User
Tags ticket

AOP Introduction AOP (Aspect oriented programming), namely aspect-oriented programming, can be said to be OOP (object oriented programming, object-oriented programming) complement and perfect. OOP introduces concepts such as encapsulation, inheritance, and polymorphism to create an object hierarchy that simulates a collection of public behavior. However, OOP only allows developers to define vertical relationships, but it is not appropriate to define horizontal relationships such as logs, transactions, security, etc. These functions are applied horizontally in the business process, and their corresponding methods are not associated with other code, such as exception handling and transparency of the continuity of the same, not only to increase the amount of code, but also for the later maintenance of the program has many difficulties.  AOP technology on the contrary, it uses a technique called "crosscutting" that splits the encapsulated object interior and encapsulates public behavior that affects multiple classes into a reusable module, named "Aspect", or tangent. The so-called "cut-off", simply said to be those unrelated to the business, but for the business module calls together the logic or responsibility to encapsulate, reduce the coupling between the modules, and conducive to future operability and maintainability.   using "crosscutting" technology, AOP divides software systems into two parts: core concerns and crosscutting concerns. The main process of business process is the core concern, and the part that has little relation is the crosscutting concern. One feature of crosscutting concerns is that they often occur in many of the core concerns and are similar everywhere, such as authority authentication, logging, and things. The role of AOP is to separate the various concerns in the system, separating the core concerns from the crosscutting concerns. Second, AOP basic understanding and notification Method 1, Aspect (Aspect): A focus on the modularity, this concern may be crosscutting multiple objects. Transaction management is a good example of a crosscutting concern in the Java EE application.     in spring AOP, facets can be implemented using schema-based or aspect annotations. Popular point is that we join the slice class (such as the log Class), so to understand. 2. Connection point (Joinpoint): A specific point during the execution of a program, such as when a method is called or when handling an exception. In spring AOP, a connection point always represents the execution of a method. In layman's words, the point 3, Notification (Advice): The action performed on a particular connection point on a tangent. These include different types of notifications such as "Around", "before", and "after" (the type of notification will be discussed later). Many of the AOP frameworks, including spring, are notification models with interceptors, and maintain an interceptor chain centered on the connection point. 4. Entry point (POINTCUT): Matches the assertion of the connection point. The notification is associated with a pointcut expression and runs on the connection point that satisfies the pointcut (for example, when a method for a particular name is executed). How Pointcut expressions match connection points is the core of AOP: Spring defaults to using the ASPECTJ pointcut syntax. 5. Introduction (Introduction): Used to declare additional methods or properties for a type (also known as a connection type declaration (Inter-type declaration)). Spring allows the introduction of new interfaces (and a corresponding implementation) to any Proxied object. For example, you can use ingestion to enable a bean to implement the IsModified interface to simplify the caching mechanism. 6. Target object: An object that is notified by one or more facets. Also called made informed (advised) objects. Since spring AOP is implemented by the runtime proxy, this object is always a proxy (proxied) object. 7. AOP Proxy: An AOP framework object created to implement a facet contract (such as notification method execution, and so on). In spring, an AOP proxy can be either a JDK dynamic agent or a cglib proxy. 8. Weave in (Weaving): Connect the facets to other application types or objects and create a notified object. These can be done at compile time (for example, with the AspectJ compiler), at class load time, and at run time. Spring, like other pure Java AOP frameworks, completes weaving at run time. Notification method: 1. Pre-notification (before advice): A notification that is executed before a connection point, but this notification does not block the execution process before the connection point (unless it throws an exception). 2. Post notification (after returning advice): Notification performed after a connection point is completed: For example, a method does not throw any exceptions and returns normally. 3. Exception notification (after throwing advice): Notification that is executed when the method throws an unexpected exit. 4. Final notification (after (finally) advice): Notifications that are executed when a connection point exits (whether it is a normal return or an abnormal exit). 5. Surround notification (Around Advice): A notification that surrounds a connection point, such as a method call. This is the most powerful type of notification. Surround notifications can accomplish custom behavior before and after a method call.   It also chooses whether to continue execution of the connection point or to return its own return value directly or throw an exception to end execution.   Spring's support for AOP in spring, the AOP agent is generated and managed by the spring IOC container, and its dependencies are also owned by the IOC container. So, the AOP proxy can use the other bean samples in the container directly as a target, which can be provided by dependency injection of the IOC container (not familiar with dependency injection can look at my previous post). The spring create proxy rule is: 1, the default is to use the JDK dynamic proxy to create an AOP proxy, so you can create proxy 2 for any interface example, and when the class that needs the proxy is not the proxy interface, spring switches to use the Cglib proxy, or it can enforce the use of the Cglib proxy. (Mandatory method: Modify the AOP attribute spring.aop.proxy-target-class=true in the XML configuration or modify @enableaspectjautoproxy in comments (Proxytargetclass = True) The key to AOP programming is defining pointcuts and defining enhanced processing, and once the appropriate pointcuts and enhancements are defined, the AOP framework automatically generates an AOP proxy, the method of Proxy objects = methods of enhanced processing + proxied objects   Iv. Spring AOP Chestnut 1, Define an interface package Com.samter.common;public interface car {void run (String name);} 2, the implementation of the interface class package Com.samter.commonimpl;public class Carimpl implements Car{ public void Run (String name) {  System.out.println ("A Car" "+name+" is racing ... ");  }   }3, slice package com.samter.aspect;import org.aspectj.lang.annotation.AfterReturning;  import Org.aspectj.lang.annotation.Aspect;  import Org.aspectj.lang.annotation.Before;  import Org.aspectj.lang.annotation.Pointcut;   @Aspect  public class Aspects {  //  First * represents all classes under all packages//  packages under the scan com.samter after any return value type. All methods within the class, methodsAll parameters of @pointcut ("Execution (* com.samter.*.*.* (..))")  public void Foundcar () {}    @Before (value= " Foundcar () ")  public void Foundbefore () { system.out.println (" traffic police "found a car racing ...");  }    @AfterReturning ("Foundcar () && args (name,..)")  public void Foundafter (String name) {  SYSTEM.OUT.PRINTLN ("Traffic police" stop, car name is "+name+" "...");  }   @AfterReturning ("Foundcar ()") public void Foundafter () {System.out.println ("Traffic police" ticket);}  }4, XML configuration   

5, test package com;  Import Org.springframework.context.ApplicationContext; Import Org.springframework.context.support.ClassPathXmlApplicationContext;   Import Com.samter.common.pig;import Com.samter.common.commo.Dog; public class Main {public static void main (string[] args) {ApplicationContext context = new Classpathxmlapplication     Context ("Bean.xml");  Car car = (car) context.getbean ("Car"); Car.run ("BMW"); }}6, the result "traffic police" found a car is racing ... A BMW is racing ... "Traffic police" stop, car name is BMW ... "Traffic police" to open a ticket 7, after 1. Do not forget to guide the jar package before running (do not go to the Internet) 2. Run an error to see if the class name is incorrectly written or if the XML file is not read, The XML is placed under the root path 3. Write Test class is careful not to guide the wrong package 8, PostScript here only write the front and back notice, other notice in addition to surround notice external method are almost, surround notice everyone can go under Baidu, online many great gods have detailed chestnut. Five, pictures

Spring Aop Detailed

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.