Spring's AOP

Source: Internet
Author: User

Aspect-oriented programming, AOP, is a programming technique that allows programmers to modularize the behavior of crosscutting concerns or crosscutting typical lines of responsibility, such as logging and transaction management. The core structure of AOP is the aspect,

It encapsulates behaviors that affect multiple classes into reusable modules.

In general, we have two ways to implement AOP.

Implementing AOP using Dynamicproxy

The following is a simple example that defines a business object first:

1 public interface Userdao {2  3     void Save (), 4} 5  6 public class Userdaoimpl implements Userdao 7 {8     PR Ivate String name; 9     public     Void Save () {One         System.out.println ("Save () is called for" + name),}13 public     void s Etname (string name) {         this.name = name;16     }17 public     String getName () {         return name;20     } 21}

The following is a class that implements the Invocationhandler:

1 public class Proxyfactory implements Invocationhandler 2 {3     Private object target, 4  5 Public     Object Create Userdao (Object target) 6     {7         this.target = target; 8         return Proxy.newproxyinstance (This.target.getClass () . getClassLoader (), 9                 this.target.getClass (). Getinterfaces (), this), and     }11     public     Object Invoke ( Object Proxy, method, object[] args)             throws Throwable {         userdaoimpl Userdao = (Userdaoimpl) target;16         Object result = null;17         if (userdao.getname ()! = null) ~         {             result = Method.invoke ( Target, args);         else22         {             System.out.println ("The name is null.");         }25         return result;26     }27}

Next is the test code:

1 private static void Test1 () 2 {3     proxyfactory pf = new Proxyfactory (); 4     Userdao Userdao = (Userdao) pf.createuserd AO (New Userdaoimpl ()); 5     Userdao.save (); 6}

The results of the implementation are as follows:

The name is null.

This is because the type of Userdao is Userdao, it is an interface, and there is no Name field defined, so name=null.

Implementing AOP using Cglib

Also the above requirements, we assume that there is no inherited interface, which we can use cglib to implement.

First we redefine a UserDaoImpl2, which does not implement any interface:

1 public class UserDaoImpl2 2 {3     private String name; 4      5 public     Void Save () throws Interruptedexception {6< C6/>thread.sleep (3000); 7         System.out.println ("Save () is called for" + name); 8     } 9 public     void SetName (string name) {         THIS.name = name;12}13 + public     String getName () {1 5         return name;16     }17     public     void RaiseException () {$         throw new RuntimeException ("This is Test.");     }22}

Then create the cglibfactory:

1 public class Cglibfactory implements Methodinterceptor 2 {3     Private object target, 4 public     object Createuserda O (Object target) 5     {6         this.target = target, 7         enhancer enhancer = new Enhancer (); 8         Enhancer.setsupercla SS (Target.getclass ()); 9         Enhancer.setcallback (this),         enhancer.create return (),}12 public     Object Intercept (object Proxy, method, object[] args,14             methodproxy methodproxy) throws Throwable {UserDaoImpl2 Userdao         = (Us ERDAOIMPL2) target;16         if (userdao.getname ()! = null) +         {             return Method.invoke (target, args); 19         }20         else21         {             System.out.println ("The name is null.");         }24         return null;25     }26}

It implements the Methodinterceptor interface, which includes the Intercept method, which triggers the target method in a reflective manner, while adding some additional processing.

Here are the test methods:

1 private static void Test2 () throws Interruptedexception 2 {3     cglibfactory CF = new Cglibfactory (); 4     Userdaoimp L2 temp = new UserDaoImpl2 (); 5     UserDaoImpl2 Userdao = (USERDAOIMPL2) Cf.createuserdao (temp); 6     Userdao.save (); 7     temp.setname ("Zhang San "); 8     Userdao = (USERDAOIMPL2) Cf.createuserdao (temp); 9     Userdao.save (); 10}

The output results are as follows:

The name is Null.save () are called for Zhang San
Using spring to implement AOP

The spring framework is a collection of proxyfactory and cglib two ways to implement AOP.

Let's take a look at an example, or use the Userdaoimpl and UserDaoImpl2 defined above.

You first need to define a interceptor:

 1 @Aspect 2 public class Myinterceptor {3 4 @Pointcut ("Execution (* sample.spring.aop.*.* (..))") 5 public void Anymethod () {} 6 7 @Before ("Anymethod ()") 8 public void before () 9 {ten System.out.println ("before"     ), one}12 @After ("Anymethod ()") ("the") and the public void after () {System.out.println ("after"); 17         }18 @Around ("Anymethod ()") public void Around (Proceedingjoinpoint pjp) throws Throwable21 {22         Long start = System.currenttimemillis (); Pjp.proceed (); Long end = System.currenttimemillis (); 25     System.out.println ("Execution Time:" + (End-start));}27 @Before ("Anymethod () && args (name)") 29 public void before (String name)-{System.out.println ("The name is" + name),}33 @After Returning (pointcut= "Anymethod ()", returning= "result"), the public void afterreturning (String result) Stem.out.println ("The VALue is "+ result",}39 @AfterThrowing (pointcut= "Anymethod ()", throwing= "E"), and the public void Afterthrow ING (Exception e) e.printstacktrace (); 44}45}

We can see that the above code contains some annotation, which are the key to implementing AOP.

Then you need to modify Beans.xml to add the following:

1 <aop:aspectj-autoproxy/>2 <bean id= "Userdaoimpl" class = "Sample.spring.aop.UserDaoImpl"/>3 <bean id= "USERDAOIMPL2" class = "sample.spring.aop.UserDaoImpl2"/>4 <bean id= "Myinterceptor" class= " Sample.spring.aop.MyInterceptor "/>

The first line is to let spring open the functionality of AOP, the following three lines define three beans, here we interceptor also as a Bean object.

Next is the test code:

1 private static void Test3 () throws Interruptedexception 2 {3     applicationcontext ctx = new Classpathxmlapplicationco ntext ("sample/spring/aop/beans.xml"); 4     Userdao Userdao = (Userdao) ctx.getbean ("Userdaoimpl"); 5     Userdao.save (); 6     UserDaoImpl2 UserDao2 = ( USERDAOIMPL2) Ctx.getbean ("UserDaoImpl2"); 7     Userdao2.save (); 8     userdao2.setname ("Zhang San"); 9     String name = Userdao2.getname ();        Userdao2.raiseexception (); 11}

Here we can see that the test method used both the USERDAOIMPL1 (here is the Userdao interface), but also used the USERDAOIMPL2. As we said above, in spring, if the class implements an interface, spring will handle it in the proxyfactory way, and if the interface is not implemented, spring will be handled in the cglib manner.

The output of the above test method is as follows:

Beforebeforesave () is called for null execution time: 1The value is nullafterafter execution time: 1The value is Nullbeforebeforesave () is called  For null execution time: 3001The value is nullafterafter execution time: 3002The value is nullbeforethe name is Zhang sanbefore execution time: 26The value is Nullafterafter Execution Time: 27The value is Nullbeforebefore execution time: 0The value is nullafterafter execution time: 1The value is null
Configuring AOP with the Spring configuration file

In the example above, we use annotation to configure the information for AOP, and we can also use XML files to configure AOP.

Or based on the interceptor defined above, we remove all of the annotation and add the following in Beans.xml:

1 <bean id= "MyInterceptor2" class= "Sample.spring.aop.MyInterceptor2"/> 2 <aop:config> 3     <AOP: Aspect id= "ASP" ref= "MyInterceptor2" > 4         <aop:pointcut id= "Anymethod" expression= "Execution (* Sample.spring.aop.*.* (..)) " /> 5         <aop:before pointcut-ref= "Anymethod" method= "before"/> 6         <aop:after pointcut-ref= " Anymethod "method=" after "/> 7         <aop:around pointcut-ref=" Anymethod "method=" Around "/> 8         <AOP: After-returning pointcut-ref= "Anymethod" method= "afterreturning" returning= "result"/> 9         <AOP: After-throwing pointcut-ref= "Anymethod" method= "afterthrowing" throwing= "E"/>10     </aop:aspect>11 </ Aop:config>

The test method and output result are as above.

Spring's AOP

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.