Spring Aop Slicing programming

Source: Internet
Author: User
Tags object object throwable

Requirements: Before the dynamic selection of the database, and now the method of a service layer access to cat, you need to use the cutting-plane programming.

Reference documents:

Http://www.blogjava.net/supercrsky/articles/174368.html

http://my.oschina.net/itblog/blog/211693

First, Introduction

Aspect-oriented programming (AOP) provides an alternative perspective for thinking about program structure, which compensates for the shortcomings of object-oriented programming (OOP). In addition to classes (classes), AOP provides facets. The focus is modular, such as the transaction management of crosscutting multiple types and objects. (These point-of-interest terms are often referred to as crosscutting (crosscutting) concerns.) )

One of the key components of spring is the AOP framework. However, the spring IOC container does not rely on AOP, which means that you are free to choose whether to use AOP,AOP to provide a powerful middleware solution, which makes the spring IOC container more complete.

  • Facets (Aspect): A focus of modularity, which may be crosscutting across 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 generic classes (pattern-based styles) or @Aspect annotations (@AspectJ styles) in ordinary classes.

  • Connection point (Joinpoint): a particular point in the execution of a program, such as when a method is called or when an exception is handled. In spring AOP, a connection point always represents the execution of a method. By declaring a parameter of type org.aspectj.lang.JoinPoint , you get the connection point information for the body part of the notification (Advice).

  • Notification (Advice): An action performed on a particular connection point (joinpoint) of a slice. Notifications are available in various types, including notifications such as "Around", "before", and "after". The type of notification is discussed later in this section. Many AOP frameworks, including spring, are notification models with interceptors, and maintain a chain of interceptors centered on the connection point.

  • Pointcut (Pointcut): an assertion that matches a connection point (Joinpoint). 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.

  • Introduced (Introduction): (also known as an internal type declaration (Inter-type declaration)). Declare additional methods or fields of a certain type. Spring allows the introduction of new interfaces (and a corresponding implementation) to any Proxied object. For example, you can use an introduction to make the bean implement the ismodified interface to simplify the caching mechanism.

  • Target object: An object that is notified (advise) by one or more facets (aspect). It is also called the notified (advised) object. Since spring AOP is implemented by the runtime proxy, this object is always a proxy (proxied) object.

  • AOP Proxy: An object created by the AOP framework to implement a facet contract (aspect contract), including functions such as notification method execution. In spring, an AOP proxy can be either a JDK dynamic agent or a cglib proxy. Note: The latest introduction to Spring 2.0 is the pattern-based (schema-based) style and @aspectj annotation style facet declarations, which are transparent to the users who use these styles.

  • Weaving (Weaving): Connects a facet (aspect) to another application type or object and creates an object that is notified (advised). 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.

Type of notification:

    • Pre-notification (before advice): A notification that is executed before a connection point, but this notification does not prevent execution before the connection point (unless it throws an exception).

    • Notification after return (after returning advice): A notification that is executed after a connection point is completed normally: for example, a method does not throw any exceptions and returns normally.

    • Notification after an exception is thrown (after throwing advice): the notification that is executed when the method throws an exception exits.

    • Post notification (after (finally) advice): A notification that is executed when a connection point exits (whether it is a normal return or an unexpected exit).

    • Surround notification (Around Advice): A notification that encloses 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 executing the connection point or to return directly to their own return value or throw an exception to end the execution.

Surround notification is one of the most common types of notifications. Most interception-based AOP frameworks, such as Nanning and JBOSS4, provide only surround notifications.

The concept of pointcut (pointcut) and connection point matching is the key to AOP, which makes AOP different from other old technologies that simply provide interception functionality. The pointcut enables the location notification (advice) to be independent of the OO hierarchy. For example, a around notification that provides declarative transaction management can be applied to a set of methods that span multiple objects, such as all business operations at the service layer.

Second, programming (there are two, based on the annotation method and the XML configuration method, the introduction of annotation-based AOP programming)

1. Configure AOP in configuration files

<?XML version= "1.0" encoding= "UTF-8"?>  <Beansxmlns= "Http://www.springframework.org/schema/beans"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"Xmlns:context= "Http://www.springframework.org/schema/context"XMLNS:AOP= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP"xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5. XSD Http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spri Ng-context-2.5.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/a Op/spring-aop-2.5.xsd ">  

2.

Package Com.abc.advice;import Java.util.arrays;import Org.aspectj.lang.joinpoint;import Org.aspectj.lang.proceedingjoinpoint;import Org.aspectj.lang.annotation.after;import Org.aspectj.lang.annotation.afterreturning;import Org.aspectj.lang.annotation.around;import Org.aspectj.lang.annotation.aspect;import Org.aspectj.lang.annotation.Before; @Aspectpublic class Advicetest {@    Around ("Execution (* com.abc.service.*.many* (..))")        Public Object process (Proceedingjoinpoint point) throws Throwable {System.out.println ("@Around: Before executing the target method ...");        Parameters for accessing the target method: object[] args = Point.getargs (); if (args! = null && args.length > 0 && args[0].getclass () = = String.class) {Args[0] = "changed        Parameter 1 ";        }//Execute the target method with the changed parameters object returnvalue = Point.proceed (args);        System.out.println ("@Around: After executing the target method ...");        System.out.println ("@Around: The target object being woven into is:" + point.gettarget ());   Return "Original returned value:" + ReturnValue + ", which is the suffix of the returned result"; } @Before ("Execution (* com.abc.service.*.many* (..))")        public void Permissioncheck (Joinpoint point) {System.out.println ("@Before: Impersonation permission check ..."); System.out.println ("@Before: Target method:" + point.getsignature (). Getdeclaringtypename () + "." +        Point.getsignature (). GetName ());        System.out.println ("@Before: Parameter:" + arrays.tostring (Point.getargs ()));    System.out.println ("@Before: The target object being woven into is:" + point.gettarget ()); } @AfterReturning (pointcut= "Execution (* com.abc.service.*.many* (..))", returning= "returnvalue") Public V        OID log (joinpoint point, Object returnvalue) {System.out.println ("@AfterReturning: Analog logging function ...");                 System.out.println ("@AfterReturning: Target method:" + point.getsignature (). Getdeclaringtypename () +        "." + point.getsignature (). GetName ());        System.out.println ("@AfterReturning: Parameter:" + arrays.tostring (Point.getargs ())); System.out.println ("@AFterreturning: The return value is: "+ returnvalue);            System.out.println ("@AfterReturning: The target object being woven into is:" + point.gettarget ());    } @After ("Execution (* com.abc.service.*.many* (..))")        public void Releaseresource (Joinpoint point) {System.out.println ("@After: Simulate releasing resources ..."); System.out.println ("@After: Target method:" + point.getsignature (). Getdeclaringtypename () + "." + P        Oint.getsignature (). GetName ());        System.out.println ("@After: Parameter:" + arrays.tostring (Point.getargs ()));    System.out.println ("@After: The target object being woven into is:" + point.gettarget ()); }}

The simplest way to access the target method is to define an enhanced processing method, define the first parameter as the Joinpoint type, and when the enhanced processing method is called, the Joinpoint parameter represents the join point for weaving the enhanced processing. The joinpoint contains the following common methods:

    • Object[] Getargs: Returns the parameters of the target method

    • Signature getsignature: Returns the signature of the target method

    • Object Gettarget: Returns the target object that was woven into the enhanced processing

    • Object Getthis: Returns the proxy object generated by the AOP framework for the target object

Note: When using @around processing, we need to define the first parameter as a proceedingjoinpoint type, which is a subclass of Joinpoint.

@Around: Before executing the target method ... @Before: Impersonation permission check ... @Before: The target method is: Com.abc.service.advicemanager.manyadvices@before: The parameter is: [ Changed parameter 1, BB] @Before: The target object to be woven into is: [email protected] Method: Manyadvices@around: After executing the target method ... @Around: The object being woven into is: [email Protected] @After: Simulate releasing resources ... @After: The target method is: com.abc.service.advicemanager.manyadvices@after: parameter: [changed parameter 1, bb]@ After: The target object to be woven into is: [email protected] @AfterReturning: Analog logging function ... @ Afterreturning: The target method is: com.abc.service.advicemanager.manyadvices@afterreturning: parameter: [changed parameter 1, bb]@ Afterreturning: The return value is: The original return value: The changed parameter 1, BB, which is the suffix of the returned result @afterreturning: The target object to be woven into: [email protected] The return value of the tangent method called in the test method: The original return value: The changed parameter 1, BB, which is the suffix of the returned result

It can be seen from the results that the information of the target method can be obtained in any of the enhanced processes of weaving. In addition, Spring AOP uses the same finite order as ASPECTJ to weave the enhanced processing: when the "enter" connection point, the highest priority of the enhanced processing will first be woven into (so given two before enhancement processing, the priority of the higher one will be executed first); When you exit the connection point, The highest priority enhancement processing is eventually woven (so the given two after enhancement processing, the one with the higher priority will be executed later). When multiple enhancements in different facets need to be woven at the same connection point, Spring AOP will weave these enhancements in a random order. If your application needs to specify the priority of enhanced processing in different slice classes, Spring provides the following two solutions:

    • Let the slice class implement the Org.springframework.core.Ordered interface: Implementing the interface requires only the implementation of an int GetOrder () method, the smaller the return value of the method, the higher the priority

    • Use @order annotations directly to decorate a slice class: When using this annotation, you can configure a Value property of type int, the smaller the value, the higher the priority

The priority of enhanced processing in high-priority slice classes is always higher than the precedence of enhanced processing in lower-priority slice classes. For example, a Bean1 with a priority of 1 contains @before, and a slice class with a priority of 2 Bean2 contains @around, although the @around priority is higher than @before, but because the Bean1 priority is higher than the Bean2 priority, So the @before in Bean1 is first woven into.

Two of the same types of enhancements in the same slice class are woven at the same connection point, and Spring AOP will weave these two enhancements in a random order, with no way to specify their weaving order. If you do need to ensure that they are woven in an intrinsic order, you might consider compressing multiple enhancements to one enhancement, or refactoring different enhancements to different facets by defining the order at the slice level.

Third, their own application

@Aspect @component Public classexampleaspect {@Around ("Execution (* ##.adapter. exampleaspect.* (..)) ")     PublicObject aroundpoint (proceedingjoinpoint pjp) {//category and method namesTransaction t = catcontainer.newtransaction ("Example", Pjp.getsignature (). GetName ()); Object Object=NULL; Try{Object=pjp.proceed (); //parameters of the target methodT.adddata ("param", Jsonobject.tojsonstring (Pjp.getargs ())); //StatusT.setstatus (message.success); //return value T.adddata ("Response", jsonobject.tojsonstring (object));}Catch(Throwable e) {catcontainer.logerror (e);        T.setstatus (e); } finally{t.complete (); }        returnobject; }}

Spring Aop plane programming

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.