Spring Note (c): an AOP explanation

Source: Internet
Author: User
Tags string methods throwable

First, the principle of AOP

(a) dynamic agent

1, see: Java Advanced (vii): detailed Java Agent

2, mainly proxy and Invocationhandle R interface


(ii) CGLIB implementation

1, mainly enhancer and Methodinterceptor interface

2, the implementation code is as follows:

<span style= "FONT-SIZE:18PX;" >/** * Using Cglib to implement * @param TARGRT * @return */public static object Getcgproxy (final Object targrt,final Advice Advice) {//Take advantage of enhancerenhancer enhancer in cglib = new enhancer ();//Set the target class as the parent of the proxy (inheriting the target class, overwriting all its non-final methods) Enhancer.setsuperclass ( Targrt.getclass ());//Set callback Enhancer.setcallback (new Methodinterceptor () {//Implement Methodinterceptor interface @overridepublic Object Intercept (Object proxy, method, object[] args, Methodproxy methodproxy) throws Throwable {Object object = Nu Ll;try{advice.before (method);//Front object = Methodproxy.invoke (Targrt, args); Advice.after (method);//Post}catch ( Exception e) {Advice.afterthrow (method);//Exception}finally{advice.afterfinally (method);//Final}return object;}}); return Enhancer.create ();} </span>

(iii) Environment and Concepts

1. Required Package: Spring package, also need Aspectjweaver.jar,aopalliance.jar, Asm.jar and Cglib.jar.

2. How AOP is implemented:Spring interface, schema configuration and annotations three ways

3. Concept

1) Tangent (aspect): A class used to interpolate business methods.

2) connection point (Joinpoint): is the aspect class and the business class connection point, in fact is encapsulates the business method some basic attribute, as the notification parameter to parse.

3) Notification (advice): in the Slice class, declare a method that does additional processing for the business method.

4) entry point (pointcut): The method specified in the business class as the point at which the tangent cuts in. is to designate a method as a tangent.

5) target object: the object being proxied.

6)AOP agent (AOP proxy): proxy object.

7) pre-notification (before advice): executed before the pointcut.

8) post notification (after returning advice): executes the notification after the Pointcut execution is complete.

9) surround notification (around advice): surrounds the Pointcut, invokes the method before and after the custom behavior is completed.

10. exception Notification (after throwing advice): executes the notification after the pointcut throws an exception.


Second, the AOP implementation of spring interface

(a) See: Spring AOP (top)

(ii) analysis

1, to achieve dependency is troublesome, spring defines a bunch of notifications interface, as long as the implementation can be. such as the front notification interface Methodbeforeadvice

<span style= "FONT-SIZE:18PX;" >package Main.java.com.spring.aop.apj;import Java.lang.reflect.method;import org.springframework.aop.methodbeforeadvice;/** * Spring Interface Pre-notification * Basebeforeadvice * @title * @desc * @author Sam-sho * @Ja N. */public class Basebeforeadvice implements Methodbeforeadvice {    /**     * method: How to cut in <br>     * A RGS: Parameters of the Cut-in method <br>     * Target: Destination Object *    /@Override public    Void Before (method, object[] args, Object target) throws Throwable {        System.out.println ("=========== into Beforeadvice () ============ \ n");        System.out.print ("Ready to use" on "+ Target +" objects);        System.out.print (method + "approach to");        System.out.print (Args[0] + "' To delete! \ n ");        System.out.println ("To enter the Pointcut method \ n");}    } </span>


2. Need to specify tangency point: Implement Interface Methodbeforeadvice

<span style= "FONT-SIZE:18PX;" >/** * Defines a pointcut that specifies the corresponding method match. To be processed for the method <br> * Inherit the  Namematchmethodpointcut class to match the method name *  * @author  *  */public class Pointcut Extends Namematchmethodpointcut {    private static final long serialversionuid = 3990456017285944475L;    @SuppressWarnings ("Rawtypes")    @Override public    Boolean matches (method, Class targetclass) {        // Sets a single method to match        this.setmappedname ("delete");        Set multiple methods        to match string[] methods = {"Delete", "modify"};                You can also use "*" to do the matching symbol        //This.setmappedname ("get*");                This.setmappednames (methods);        Return Super.matches (method, Targetclass);}    } </span>

3, need to configure. Very troublesome.


Third, Spring uses ASPECTJ to realize AOP

(a) Source code

1. Business Class (target)

<span style= "FONT-SIZE:18PX;"  >package main.java.com.spring.aop.service;/** * Business interface * Personservice * @title * @desc * @author Sam-sho * @Jan 17, 2015 */public interface Personservice {/** * Save user entity * @param name */public void Save (String name);/** * Delete User entity * @param ID */p ublic void Delete (integer ID);/** * Query number is ID for use user name * @param ID */public String querypersonname (integer ID);/** * Update entity * @p Aram name * @param id */public void Update (String name, Integer ID);} </span>

<span style= "FONT-SIZE:18PX;" >package Main.java.com.spring.aop.service.impl;import main.java.com.spring.aop.service.personservice;/** * Business Implementation class * Persionserviceimpl * @title * @desc * @author Sam-sho * @Jan, */public class Personserviceimpl implements Personservice {@Overridepublic void Save (String name) {System.out.println ("I Am the Save () method");} @Overridepublic void Delete (Integer id) {System.out.println ("I am the Delete () method");} @Overridepublic String querypersonname (Integer id) {System.out.println ("I am the query () method"); return "XXX";} @Overridepublic void Update (String name, Integer ID) {System.out.println ("I Am the update () method");}} </span>

2, Slice class ( aspect: class internal definition of various notifications advice)

<span style= "FONT-SIZE:18PX;" >package Main.java.com.spring.aop.apj;import Org.aspectj.lang.joinpoint;import  org.aspectj.lang.proceedingjoinpoint;/** * * Aspectadvice * @title Slice class * @desc * @author Sam-sho * @Jan One, */public Class Aspectadvice {/** * pre-notification * * @param JP */public void Dobefore (Joinpoint jp) {Syste        M.out.println ("=========== into before advice============ \ n");        System.out.println ("Ready on" + Jp.gettarget (). GetClass () + "Object");        System.out.println (Jp.getsignature (). GetName () + "method to"); System.out.println (Jp.getargs () [0] + "' Delete!        \ n ");    System.out.println ("To enter the Pointcut method \ n"); }/** * Post notification * * @param JP * Connection point * @param result * return value */public        void Doafter (Joinpoint JP, String result) {System.out.println ("========== into after advice=========== \ n");        System.out.println ("The Pointcut method has been executed \ n");        System.out.print (Jp.getargs () [0] + "in"); SysteM.out.print (Jp.gettarget (). GetClass () + "on object");        System.out.print (Jp.getsignature (). GetName () + "method removed");    System.out.print ("Left only:" + result + "\ n"); }/** * Surround notification * * @param PJP * Connection point */public void Doaround (Proceedingjoinpoint pjp) t Hrows throwable {System.out.println ("=========== into around surround Method!        =========== \ n "); Call the target method before executing the action System.out.println ("Before calling the method: Execute!")        \ n ");        parameter of the calling method object[] args = Pjp.getargs ();        The method name of the call is String methods = Pjp.getsignature (). GetName ();        Gets the target objects object target = Pjp.gettarget ();        Executes the return value of the method: invokes the proceed () method, which triggers the Pointcut method to execute Object result = Pjp.proceed (); System.out.println ("Call method End: Execute after!")                \ n ");            System.out.println ("Output:" + args[0] + ";" + method + ";" + target + ";" + result + "\ n");        }/** * Exception notification * * @param JP * @param e */public void Dothrow (Joinpoint JP, Throwable e) { SysteM.out.println ("delete error"); }}</span>


3, configuration.

<span style= "FONT-SIZE:18PX;" > <!--declaring a business class bean--<bean id= "Personservice" class= "Main.java.com.spring.aop.service.impl.PersonServ     Iceimpl "/> <!--notice class--<bean id=" Aspectadvice "class=" Main.java.com.spring.aop.apj.AspectAdvice "/> <aop:config> <aop:aspect id= "Businessaspect" ref= "Aspectadvice" > <!--configuration Specifies the object to cut in--&gt            ; <aop:pointcut id= "point_cut" expression= "Execution (* main.java.com.spring.aop.service). *.*(..))" /> <!--match only the Add method as a pointcut-<!--<aop:pointcut id= "Except_add" expression= "Execution (* Aop.schema.*.add (..)) "            />-<!--pre-notification-<aop:before method= "Dobefore" pointcut-ref= "Point_cut"/> <!--post notification returning specify return parameters-<!--<aop:after-returning method= "Doafter" pointcut-ref= "Poin T_cut "returning=" result "/>-<!--surround-<!--<aop:arounD method= "Doaround" pointcut-ref= "Point_cut"/>-<!--throw--<!--<aop:after -throwing method= "Dothrow" pointcut-ref= "Point_cut" throwing= "E"/>-</aop:aspect> </aop:config ></span>


4, Test.

<span style= "FONT-SIZE:18PX;" > @Testpublic void Soptest () {ApplicationContext cxt = new Classpathxmlapplicationcontext (" Applicationaopcontext.xml "); Personservice Personservice = (personservice) cxt.getbean ("Personservice");p ersonservice.save ("Shaoxiaobao ...");// Taspectbusiness.delete ("Zhaoxioaniu");} </span>



Iv. Annotations for AOP

(i) Implementation of the configuration

1, the automatic scanning, annotations to implement the bean management and injection. (Targets and facets are managed by spring)

<span style= "FONT-SIZE:18PX;" >    <!--automatic scanning--    <context:component-scan base-package= "main.java.com.spring"/></span >

2. Development of AOP annotations

<span style= "FONT-SIZE:18PX;" >    <!--open AOP annotations--    <aop:aspectj-autoproxy/></span>

(b) Annotations implement slice classes.

<span style= "FONT-SIZE:18PX;" >package Main.java.com.spring.aop.apj;import Org.aspectj.lang.joinpoint;import Org.aspectj.lang.proceedingjoinpoint;import Org.aspectj.lang.annotation.afterreturning;import Org.aspectj.lang.annotation.afterthrowing;import Org.aspectj.lang.annotation.around;import Org.aspectj.lang.annotation.aspect;import Org.aspectj.lang.annotation.before;import Org.aspectj.lang.annotation.pointcut;import org.springframework.stereotype.Component; @Component//     Let Spring management bean@aspect//define the Slice class public class Annotationaspectadvice {/* * Specify pointcut matching expressions, note that it is declared in the form of a method.     * Analysis: * Execution is the method of weaving the language * First *: return any type * Main.java.com.spring.aop.service: Package. *  ..     : Service package and its child packages.     * Second *: Service package and any class under its sub-package.     * Third *: Any method of the service package and any class under its child package.     * (..): The parameters of the method are arbitrary. * Summary: The Main.java.com.spring.aop.service package and any of the classes under its sub-package are cut in/@Pointcut ("Execution (* main.java.com.spring.aop.serv Ice..    *.*(..))")     public void Anymethod () {}/** * pre-notification* * @param JP */@Before (value = "Execution" (* main.java.com.spring.aop.service).    *.*(..))")        public void Dobefore (Joinpoint jp) {System.out.println ("=========== into before advice============ \ n");        System.out.print ("Ready on" + Jp.gettarget (). GetClass () + "Object");        System.out.print (Jp.getsignature (). GetName () + "method to"); System.out.print (Jp.getargs () [0] + "' Delete!        \ n ");    System.out.println ("To enter the Pointcut method \ n"); }/** * Post notification * * @param JP * Connection point * @param result * return value */@AfterR Eturning (value = "Anymethod ()", returning = "result") public void Doafter (Joinpoint JP, String result) {System.        Out.println ("========== into after advice=========== \ n");        System.out.println ("The Pointcut method has been executed \ n");        System.out.print (Jp.getargs () [0] + "in");        System.out.print (Jp.gettarget (). GetClass () + "on object");        System.out.print (Jp.getsignature (). GetName () + "method removed"); System.out.print ("Leave only:" + Result + "\ n"); }/** * Surround notification * * @param PJP * Connection point */@Around (value = "Execution" (* main.java.com.spri Ng.aop.service.    *.*(..))") public void Doaround (Proceedingjoinpoint pjp) throws Throwable {System.out.println ("=========== into around surround Method!        =========== \ n "); Call the target method before executing the action System.out.println ("Before calling the method: Execute!")        \ n ");        parameter of the calling method object[] args = Pjp.getargs ();        The method name of the call is String methods = Pjp.getsignature (). GetName ();        Gets the target objects object target = Pjp.gettarget ();        Executes the return value of the method: invokes the proceed () method, which triggers the Pointcut method to execute Object result = Pjp.proceed ();        System.out.println ("Output:" + args[0] + ";" + method + ";" + target + ";" + result + "\ n"); System.out.println ("Call method End: Execute after!")    \ n "); }/** * Exception notification * * @param JP * @param e */@AfterThrowing (value = "Execution" (* main.java.com.spri Ng.aop.service.*.* (..)) ", throwing =" E ") public void Dothrow (Joinpoint JP, Throwable e) {System.out.println ("delete error"); }}</span>

1, Joinpoint: entry point, you can get the information to cut into the proxy object

1) Getargs (): Gets the method parameter.

2) Gettarget (): Gets the target object.

3) getsignature (): Get the method.


2, Proceedingjoinpoint: The use of the wrapping method.

1) Proceed (): The method that executes the target object.


3, Throwable: abnormal access.



Spring Note (c): an AOP explanation

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.