[Spring Frame] Spring AOP Basics Primer Two: Spring's development of ASPECTJ-based AOP.

Source: Internet
Author: User
Tags aop getmessage throwable

Objective:
In the previous article: [Spring Framework]spring An introduction to AOP basics. We already know how a spring AOP program is developed, and here we will summarize and learn AOP based on ASPECTJ.

One, AspectJ's Overview:

ASPECTJ is a tangent-oriented framework that extends the Java language. ASPECTJ defines the AOP syntax so it has a dedicated compiler to generate class files that conform to the Java Byte encoding specification.

In order to simplify the development of its own AOP, Spring takes ASPECTJ as an AOP development of spring itself.

Two, Spring ASPECTJ Development Example

2.1 Development of the required jar package



2.2 AspectJ Annotation Development specification

2.2.1 @AspectJ provide different types of notifications

@Before pre-notification, equivalent to Beforeadvice
  Complete an operation before executing the target method to obtain the pointcut information.

@AfterReturning post notification, equivalent to Afterreturningadvice

1 completes an operation after the target method executes, obtaining the return value of the method. 2 3 @AfterReturning (value= "Execution (* cn.augmentum.aspectj.demo1.customerservice+). Update (..)) ", returning=" result ") 4 public void afterreturing (Object result) {5     System.out.println (" Post notification ========= = = = "+result); 6}

@Around surround notification, equivalent to Methodinterceptor

1 An action is completed before and after the target method executes, preventing the target method from executing. 2 3 @Around (value= "Execution (* cn.augmentum.aspectj.demo1.customerservice+.delete (..))") 4 public Object Around (Proceedingjoinpoint joinpoint) throws throwable{5     System.out.println ("Notice ========== before wrapping"); 6     Object obj = Joinpoint.proceed (); 7     SYSTEM.OUT.PRINTLN ("Surround notification =========="); 8     return obj;9}


@AfterThrowing throw notification, equivalent to Throwadvice

1 When an exception occurs in the target method, complete an operation. Get exception information. 2 3 @AfterThrowing (value= "Execution (* cn.itcast.aspectj.demo1.customerservice+.find (..))" , throwing= "E") 4 public void afterthrowing (Throwable e) {5     System.out.println ("Exception throw notification =========" +e.getmessage ()); 4?

@After Final Final Notice, whether or not it is an exception, the notification will execute

1 The action that will be performed under any circumstances of the target method. Equivalent to the code in finally. 2 3 @After (value= "Execution (* cn.itcast.aspectj.demo1.customerservice+.find (..))") 4 public void After () {5     System.out.println ("Final Notice ==========="); 6}


2.2.2 Enable @aspectj facets by configuration

1 <?xml version= "1.0" encoding= "UTF-8"?> 2 <beans xmlns= "Http://www.springframework.org/schema/beans" 3        Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" 4        xmlns:aop= "http://www.springframework.org/schema/ AOP "5        xsi:schemalocation=" Http://www.springframework.org/schema/beans 6     http://www.springframework.org/ Schema/beans/spring-beans.xsd 7     HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP 8/     http Www.springframework.org/schema/aop/spring-aop.xsd "> 9     <!--turn on ASPECTJ auto Agent---     <AOP: Aspectj-autoproxy/>11 </beans>

2.2.3 defining pointcuts through the Value property in notifications

By using the execution function, you can define the tangent point method
Grammar:
Execution (< access modifier >?< return type >< method name > (< parameter >) < exception >)
For example
Match all class public methods Execution (public * * (..))
Matches all class methods under the specified package execution (* cn.itcast.dao.* (..)) does not contain child packages
Execution (* Cn.itcast.dao). *(..)) .. * Indicates the package, the descendants of all classes
Matches all methods of the specified class execution (* cn.itcast.service.userservice.* (..))
Matching implements a specific interface for all class methods Execution (* cn.itcast.dao.genericdao+.* (..))
Match all Save start Methods Execution (* save* (..))

2.2.4 AspectJ's entry point:

1 An expression that unifies the management pointcut. 2 @Pointcut (value= "Execution (* cn.itcast.aspectj.demo1.customerservice+.find (..))") 3 private void MyPointcut1 () {}//This class has no practical purpose, just for @pointcut annotations


2.2.6 the difference between aspect and advisor:

Advisor: traditional facets. Traditional facets are typically made up of a combination of a pointcut and a notification.
Aspect: The true aspect of the plane. A combination of multiple pointcuts and multiple notifications.



2.3 Spring ASPCTJ development based on annotation pattern
Customerservice.java:

1 public interface CustomerService {2 3 public     Void Save (), 4 public     Integer Update (), 5 public     void Delete (); 6 Public     void Find (); 7}

Customerserviceimpl.java:

1 public class Customerserviceimpl implements CustomerService {2  3     @Override 4 public     void Save () {5         S YSTEM.OUT.PRINTLN ("Save Customer ..."); 6     } 7  8     @Override 9 public     Integer Update () {         System.out.println ("Modify Customer ...")         return 100;12     }13     @Override15 public     void Delete () {         System.out.println ("Delete Customer ..."); 17     }18     @Override20 public     Void Find () {         System.out.println ("Query Customer ...");         int d = 1/0;23< C27/>}24 25}

Myaspectanno.java:

 1/** 2 * Custom Slice class: 3 * 4 */5 @Aspect 6 public class Myaspectanno {7 8 @Before (value= "Execution (* cn.augmentum.as Pectj.demo1.customerservice+.save (..)) ") 9 public void before (Joinpoint joinpoint) {System.out.println ("Pre-notification ============" +joinpoint); 11}12 1 3 @AfterReturning (value= "Execution (* cn.augmentum.aspectj.demo1.customerservice+.update (..))", returning= "result" ) public void afterreturing (Object result) {System.out.println ("Post-notification ============" +result); 16}17 1 8 @Around (value= "Execution (* cn.augmentum.aspectj.demo1.customerservice+.delete (..))") Public Object Around (Proceedingjoinpoint joinpoint) throws Throwable{20 System.out.println ("Surround notification ==========     "); Object obj = Joinpoint.proceed (); System.out.println (" Notify ========== after Surround "), return obj;24 }25 @AfterThrowing (value= "myaspectanno.mypointcut1 ()", throwing= "E"), public void afterthrowing (THROWABL E e) {SysteM.OUT.PRINTLN ("Exception throw notification =========" +e.getmessage ());}30 @After (value= "myaspectanno.mypointcut1 ()") LIC void after () {System.out.println ("Final Notice ==========="),}35 @Pointcut (value= "Execution (* cn.au Gmentum.aspectj.demo1.customerservice+.find (..)) ") PNs private void MyPointcut1 () {}38}

Springdemo.java Test class:

1 @RunWith (Springjunit4classrunner.class) 2 @ContextConfiguration ("Classpath:applicationContext.xml") 3 public class SpringDemo1 {4  5     @Resource (name = "CustomerService") 6     private customerservice customerservice; 7  8     @Test 9 public     void Demo1 () {         customerservice.save ();         customerservice.update ();         Customerservice.delete ();         customerservice.find ();     }15}


Applicationcontext.xml configuration file:

1 <?xml version= "1.0" encoding= "UTF-8"?> 2 <beans xmlns= "Http://www.springframework.org/schema/beans" 3        Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" 4        xmlns:aop= "http://www.springframework.org/schema/ AOP "5        xsi:schemalocation=" 6 Http://www.springframework.org/schema/beans http://www.springframework.org/ Schema/beans/spring-beans.xsd 7 HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/ Aop/spring-aop.xsd "> 8      9     <!--using annotations to complete the development of AOP-->10     <aop:aspectj-autoproxy/>11     12     <!--target object-->13     <bean id= "customerservice" class= "Cn.augmentum.aspectj.demo1.CustomerServiceImpl "/>14     <!--configuration facets-->16     <bean id=" Myaspectanno "class=" Cn.augmentum.aspectj.demo1.MyAspectAnno "/>17 </beans>


2.4 Spring ASPCTJ development based on XML Schema

Orderservice.java:

1 public class OrderService {2 public     void Save () {3         System.out.println ("Save Order ..."); 4     } 5 public     Integer Update () {6         System.out.println ("Modify order ..."); 7         return; 8     } 9 public     void Delete () {         System.out.println ("Delete order ...");     }12     Public void Find () {         System.out.println ("Query order ...");         //int d = 1/0;15     }16}

Myaspectxml.java:

1 public class Myaspectxml {2  3 public     Void before () {4         System.out.println ("Pre-notification ==========="); 5     } 6
   7 public     void afterreturing (Object result) {8         System.out.println ("Post notification ===========" +result); 9     }10 One public     Object around (Proceedingjoinpoint joinpoint) throws throwable{12         System.out.println ("wrapping Before notification = ========= ");         Object obj = Joinpoint.proceed ();         System.out.println (" Notify ========== after Surround ");         obj;16     }17     public     void afterthrowing (Throwable e) {         System.out.println ("Exception throw notification ========" + E.getmessage ());     }21 public     void after     () {         System.out.println ("Final Notice =========="); 24     }25}

Springdemo.java Test class:

1 @RunWith (Springjunit4classrunner.class) 2 @ContextConfiguration ("Classpath:applicationContext.xml") 3 public class SpringDemo2 {4  5     @Resource (name= "OrderService") 6     private OrderService OrderService; 7      8     @Test 9 Public     void Demo1 () {         orderservice.save ();         orderservice.update ();         orderservice.delete (); 13         Orderservice.find ();     15}

Applicationcontext.xml configuration file:

 1 <?xml version= "1.0" encoding= "UTF-8"?> 2 <beans xmlns= "Http://www.springframework.org/schema/beans" 3 x        Mlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" 5 xsi:schemalocation= "6 Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans.xsd 7 HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/ Spring-aop.xsd "> 8 9 <!--configuration target class-->10 <bean id=" OrderService "class=" cn.augmentum.aspectj.demo2.o Rderservice "></bean>11 <!--configuration facets-->13 <bean id=" Myaspectxml "class=" Cn.augmentum.aspectj.dem O2. Myaspectxml "></bean>14 <!--AOP configuration-->16 <aop:config>17 <aop:pointcut Expressio n= "Execution (* cn.augmentum.aspectj.demo2.OrderService.save (..))" id= "POINTCUT1"/>18 <aop:pointcut Expressio n= "Execution (* Cn.augmentum.aspectj.demo2.OrderSErvice.update (..)) " Id= "Pointcut2"/>19 <aop:pointcut expression= "Execution (* cn.augmentum.aspectj.demo2.OrderService.delete (..) ) "id=" Pointcut3 "/>20 <aop:pointcut expression=" Execution (* cn.augmentum.aspectj.demo2.OrderService.find (... ) "id=" Pointcut4 "/>21 <aop:aspect ref=" Myaspectxml ">22 <aop:before method=" before "Pointc ut-ref= "POINTCUT1"/>23 <aop:after-returning method= "afterreturing" pointcut-ref= "Pointcut2" returning= "R Esult "/>24 <aop:around method=" Around "pointcut-ref=" Pointcut3 "/>25 <aop:after-throwin G method= "afterthrowing" pointcut-ref= "Pointcut4" throwing= "E"/>26 <aop:after method= "after" Pointcut-re f= "Pointcut4"/>27 </aop:aspect>28 </aop:config>29 </beans>

[Spring Frame] Spring AOP Basics Primer Two: Spring's development of ASPECTJ-based 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.