Spring's AspectJ AOP, based on annotations (9.1) key to mastering

Source: Internet
Author: User
Tags getmessage string find stub throwable

What is ASPECTJ

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.
ASPECTJ is an AOP framework based on the Java language
Spring2.0 added support for aspectj pointcut expressions
@AspectJ is a new feature of AspectJ1.5 that allows you to define facets directly in the bean class through the JDK5 annotation technology
New version of Spring Framework, we recommend using ASPECTJ approach to develop AOP

    • ASPECTJ expression:

      • Syntax: Execution (expression)
        Execution (< access modifier >?< return type >< method name > (< parameter >) < exception >)

      • Execution (" Cn.itcast.spring3.demo1.dao. (..)”) ---Retrieve only the current package
      • Execution (" Cn.itcast.spring3.demo1.dao . (..)”) ---Retrieves the package and the child packages of the current package.
      • Execution ( cn.itcast.dao.genericdao+. (..)) ---retrieving Genericdao and sub-classes
    • ASPECTJ Enhancements:
        @Before 前置通知,相当于BeforeAdvice        @AfterReturning 后置通知,相当于AfterReturningAdvice        @Around 环绕通知,相当于MethodInterceptor        @AfterThrowing抛出通知,相当于ThrowAdvice        @After 最终final通知,不管是否异常,该通知都会执行        @DeclareParents 引介通知,相当于IntroductionInterceptor (不要求掌握)
Based on annotations
    • The first step: introduce the corresponding jar package.

      • ASPECTJ relies on an AOP environment.
      • Spring-aspects-3.2.0.release.jar
      • Com.springsource.org.aspectj.weaver-1.6.8.release.jar
    • Step Two: Write the class that is enhanced:
      • Userdao
package cn.spring3.demo1;/** * @author NOP * 被代理的对象 */public class UserDao {    public void add() {        // TODO Auto-generated method stub        System.out.println("添加客户");    }    public void delete() {        // TODO Auto-generated method stub        System.out.println("删除客户");        int i=1/0;    }    public String find() {        // TODO Auto-generated method stub        System.out.println("查询客户");        return "fanhuizhi";    }    public void update() {        // TODO Auto-generated method stub        System.out.println("修改客户");    }}
    • Step three: Use the AspectJ annotation form:
Package Cn.spring3.demo1;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.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;/** * @author NOP Slice class: Is the tangent point and the enhanced combination * Front enhancement */@Aspectpublic class Myaspect {@Before (VA Lue = "Execution (* cn.spring3.demo1.UserDao.add (..))")    Write the expression here, write which classes need to add public void before (Joinpoint joinpoint) {System.out.println ("Pre-enhancement ..." +joinpoint);    } @AfterReturning (value = "Execution (* cn.spring3.demo1.UserDao.find (..))", returning= "returnval")//write an expression here, write which classes need to be added    public void afterreturning (Object returnval) {System.out.println ("post enhancement ..." + "method return value" +returnval); } @Around (value = "Execution (* cn.spring3.demo1.UserDao.delete (..))") Write the expression here, write which classes need to add public ObjectAround (Proceedingjoinpoint proceedingjoinpoint) throws throwable{System.out.println ("Surround before enhanced ...");        Object obj = Proceedingjoinpoint.proceed ();        SYSTEM.OUT.PRINTLN ("Surround enhanced ...");    return obj; } @AfterThrowing (value = "Execution (* cn.spring3.demo1.UserDao.delete (..))", throwing= "ex")//write the expression here, write which classes need to add public V    OID afterthrowing (Throwable ex) throws throwable{System.out.println ("Don't run out of exception ..." +ex.getmessage ()); }//@After (value = "Execution (* cn.spring3.demo1.UserDao.delete (..))") Write the expression here, write which classes need to add @After ("Myaspect.mypointcut ()")//Class name. Method name public void after () {System.out.println ("final Notice");//No    Any exception will be notified}//only to define a common expression @Pointcut (value = "Execution (* cn.spring3.demo1.UserDao.delete (..))") private void Mypointcut () {}}
    • Fourth Step: Create Applicationcontext.xml
 xmlns:aop="http://www.springframework.org/schema/aop"* 引入aop的约束:*<!-- 自动生成代理  底层就是AnnotationAwareAspectJautoProxyCreator -->    <aop:aspectj-autoproxy/>    <bean id="userDao" class="cn.spring3.demo1.UserDao"/>    <bean id="MyAspect" class="cn.spring3.demo1.MyAspect"/>
    • Fifth step, write the test class
Package Cn.spring3.demo1;import Org.junit.test;import Org.junit.runner.runwith;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.beans.factory.annotation.qualifier;import Org.springframework.test.context.contextconfiguration;import org.springframework.test.context.junit4.springjunit4classrunner;/** * @author NOP * Automatic mode agent without tangent plane enhancement */@RunWith (    Springjunit4classrunner.class) @ContextConfiguration ("Classpath:applicationContext.xml") public class SpringTest1 {    @Autowired @Qualifier ("Userdao") private Userdao Userdao;        @Test public void Demo1 () {System.out.println ("-----------------");        Userdao.add ();        System.out.println ("-----------------");        Userdao.find ();        System.out.println ("-----------------");        Userdao.delete ();        System.out.println ("-----------------");        Userdao.update ();    System.out.println ("-----------------"); }} Test Result:-----------------pre-enhancement ... execution (void Cn.spring3.demo1.UseRdao.add ()) Add Customer-----------------query Customer Post enhancements ... The return value of the Fanhuizhi method is enhanced before the-----------------wrap ... Delete Customer Final Notice don't run out of exception .../by zero
    • ASPECTJ type of notification:
      • @Before pre-notification, equivalent to Beforeadvice
        • Just before the method is executed. There is no way to prevent the target method from executing.
      • @AfterReturning post notification, equivalent to Afterreturningadvice
        • After the notification, get the method return value.
      • @Around surround notification, equivalent to Methodinterceptor
        • Executes before and after a method can be done, and can prevent the execution of the target method.
      • @AfterThrowing throw notification, equivalent to Throwadvice
      • @After Final Final Notice, whether or not it is an exception, the notification will execute
      • @DeclareParents referral notification, equivalent to Introductioninterceptor (not required to master)
    • Definition of Tangent point:
      • @Pointcut ("Execution (* cn.itcast.spring3.demo1.UserDao.find (..))")
        private void Mypointcut () {}

Interview:

    • What is the difference between advisor and aspect?
      • Advisor:spring traditional facets: supports a tangent point and a combination of notifications.
      • Aspect: A combination of multiple pointcuts and multiple notifications can be supported
Based on XML
    • First step: Write the Enhanced class:
      • Productdao
package cn.spring3.demo2;public class ProductDao {    public void add() {        // TODO Auto-generated method stub        System.out.println("添加商品");    }    public void delete() {        // TODO Auto-generated method stub        System.out.println("删除商品");    }    public void find() {        // TODO Auto-generated method stub        System.out.println("查询商品");        int i = 1 / 0;    }    public String update() {        // TODO Auto-generated method stub        System.out.println("修改商品");        return "woshitest";    }}
    • Step Two: Define Facets
package cn.spring3.demo2;import org.aspectj.lang.ProceedingJoinPoint;/** * @author NOP * 切面类 */public class MyAspectXML {    /*     *      */    public void before(){        System.out.println("前置增强");    }    public void afterReturning(Object returnVal){        System.out.println("后置增强"+returnVal);    }    public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{        System.out.println("环绕前增强");        Object obj = proceedingJoinPoint.proceed();        System.out.println("环绕后增强");        return obj;    }    public void afterThrowing(Throwable ex){        System.out.println("不跑了出异常了..."+ex.getMessage());    }    public void after(){        System.out.println("最终通知");//不管有没有异常都会通知    }}
    • Step Three: Configure Applicationcontext.xml
<!--define enhanced classes--<bean id= "Productdao" class= "Cn.spring3.demo2.ProductDao"/> <!--define facets---< Bean id= "Myaspectxml" class= "Cn.spring3.demo2.MyAspectXML"/> <!--define AOP configuration-<aop:config> &lt ;!         --Define Pointcuts:--<aop:pointcut expression= "Execution (* cn.spring3.demo2.ProductDao.add (..))" id= "Mypointcut"/> <!--defining pointcuts:-<aop:pointcut expression= "Execution (* cn.spring3.demo2.ProductDao.update (..))" Id= " Mypointcutar "/> <!--defining pointcuts:--<aop:pointcut expression=" Execution (* Cn.spring3.demo2.ProductDao . Delete (..)) " Id= "Mypointcutaar"/> <!--defining pointcuts:--<aop:pointcut expression= "Execution (* cn.spring3.demo2.Produ Ctdao.find (..)) " Id= "Mypointcutaat"/> <aop:aspect ref= "Myaspectxml" > <!--pre-notification--<aop:befor E method= "Before" pointcut-ref= "Mypointcut"/> <!--post Notification--<aop:after-returning method= "afterreturning" pointcut-ref= "Mypointcutar" returning= "ReturnVal"/> <!--surround Notifications- <aop:around method= "Around" pointcut-ref= "Mypointcutaar"/> <!--exception notification--<aop:after -throwing method= "afterthrowing" throwing= "ex" pointcut-ref= "Mypointcutaat"/> <!--Final Notice//no exception will notify--&G            T <aop:after method= "after" pointcut-ref= "Mypointcutaat"/> </aop:aspect> </aop:config>
    • Fourth Step: Writing the test class
Package Cn.spring3.demo2;import Org.junit.test;import Org.junit.runner.runwith;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.beans.factory.annotation.qualifier;import Org.springframework.test.context.contextconfiguration;import Org.springframework.test.context.junit4.SpringJUnit4ClassRunner, @RunWith (Springjunit4classrunner.class) @ Contextconfiguration ("Classpath:applicationContext2.xml") public class SpringTest2 {@Autowired @Qualifier ("productd    AO ") Private Productdao Productdao;        @Test public void Demo1 () {System.out.println ("-----------------");        Productdao.add ();        System.out.println ("-----------------");        Productdao.find ();        System.out.println ("-----------------");        Productdao.delete ();        System.out.println ("-----------------");        Productdao.update ();    System.out.println ("-----------------"); }} Test Result:-----------------pre-enhancement Add commodity-----------------Query the product does not run out of the abnormal .../by zero final notification

Spring's AspectJ AOP, based on annotations (9.1) Key Mastery

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.