Spring AOP Instances

Source: Internet
Author: User
Tags throw exception throwable

One, the XML way

1. Testaspect: Slice Class

 PackageCOM.SPRING.AOP;ImportOrg.aspectj.lang.JoinPoint;ImportOrg.aspectj.lang.ProceedingJoinPoint; Public classTestaspect { Public voidDoafter (joinpoint JP) {System.out.println ("Log Ending Method:" + Jp.gettarget (). GetClass (). GetName () + "." +jp.getsignature (). GetName ()); }     PublicObject Doaround (Proceedingjoinpoint PJP)throwsThrowable {LongTime =System.currenttimemillis (); Object RetVal=pjp.proceed (); time= System.currenttimemillis ()-Time ; System.out.println ("Process time:" + time + "MS"); returnRetVal; }     Public voidDobefore (joinpoint JP) {System.out.println ("Log begining Method:" + Jp.gettarget (). GetClass (). GetName () + "." +jp.getsignature (). GetName ()); }     Public voiddothrowing (joinpoint JP, Throwable ex) {System.out.println ("Method" + jp.gettarget (). GetClass (). GetName () + "." + jp.getsignature (). GetName () + "Throw exception");    System.out.println (Ex.getmessage ()); }}

2. Aserviceimpl: Target Object

 Package Com.spring.service; // using the JDK dynamic agent  Public class Implements Aservice {    publicvoid  BarA () {        System.out.println (" Aserviceimpl.bara () ");    }      Public void Fooa (String _msg) {        System.out.println ("Aserviceimpl.fooa (msg:" + _msg + ")");}    }

3. Bserviceimpl: Target Object

 PackageCom.spring.service;//using Cglib Public classBserviceimpl { Public voidBarB (String _msg,int_type) {System.out.println ("Bserviceimpl.barb (msg:" + _msg + "type:" + _type + ")"); if(_type = = 1)            Throw NewIllegalArgumentException ("Test Exception"); }     Public voidFoob () {System.out.println ("Bserviceimpl.foob ()"); }}

4. applicationcontext:spring configuration file

<?XML version= "1.0" encoding= "UTF-8"?><Beansxmlns= "Http://www.springframework.org/schema/beans"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"XMLNS:AOP= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP"Xmlns:context= "Http://www.springframework.org/schema/context"Xmlns:tx= "Http://www.springframework.org/schema/tx"xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-3.1.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/ Spring-aop-3.1.xsd Http://www.springframework.org/schema/context http://www.springframework.org/schema/context/ Spring-context-3.1.xsd Http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/ Spring-tx-3.1.xsd ">    <Aop:config>        <Aop:aspectID= "Testaspect"ref= "Aspectbean">            <!--Configure all methods for all classes or interfaces under the Com.spring.service package -            <Aop:pointcutID= "Businessservice"expression= "Execution (* com.spring.service.*.* (..))" />            <Aop:beforePointcut-ref= "Businessservice"Method= "Dobefore"/>            <Aop:afterPointcut-ref= "Businessservice"Method= "Doafter"/>            <Aop:aroundPointcut-ref= "Businessservice"Method= "Doaround"/>            <aop:after-throwingPointcut-ref= "Businessservice"Method= "Dothrowing"throwing= "Ex"/>        </Aop:aspect>    </Aop:config>        <BeanID= "Aspectbean"class= "Com.spring.aop.TestAspect" />    <BeanID= "Aservice"class= "Com.spring.service.AServiceImpl"></Bean>    <BeanID= "Bservice"class= "Com.spring.service.BServiceImpl"></Bean></Beans>

Second, the annotation (Annotation) way

1. Testannotationaspect

 PackageCOM.SPRING.AOP;ImportOrg.aspectj.lang.ProceedingJoinPoint;ImportOrg.aspectj.lang.annotation.After;Importorg.aspectj.lang.annotation.AfterReturning;Importorg.aspectj.lang.annotation.AfterThrowing;ImportOrg.aspectj.lang.annotation.Around;ImportOrg.aspectj.lang.annotation.Aspect;ImportOrg.aspectj.lang.annotation.Before;Importorg.aspectj.lang.annotation.Pointcut; @Aspect Public classtestannotationaspect {@Pointcut ("Execution (* com.spring.service.*.* (..))")    Private voidPointcutmethod () {}//declaring a pre-notification@Before ("Pointcutmethod ()")     Public voidDobefore () {System.out.println ("Pre-notification"); }    //declaring a post-notification@AfterReturning (pointcut = "Pointcutmethod ()", returning = "Result")     Public voiddoafterreturning (String result) {System.out.println ("Post Notification"); System.out.println ("---" + result + "---"); }    //declaring exception Notifications@AfterThrowing (pointcut = "Pointcutmethod ()", throwing = "E")     Public voiddoafterthrowing (Exception e) {System.out.println ("Exception Notification");    System.out.println (E.getmessage ()); }    //declaring Final Notice@After ("Pointcutmethod ()")     Public voidDoafter () {System.out.println ("Final Notice"); }    //declaring surround Notifications@Around ("Pointcutmethod ()")     PublicObject Doaround (Proceedingjoinpoint PJP)throwsthrowable {System.out.println ("Enter method---surround Notification"); Object o=pjp.proceed (); System.out.println ("Exit Method---Surround Notification"); returno; }}

2. applicationcontext:spring configuration file

<?XML version= "1.0" encoding= "UTF-8"?><Beansxmlns= "Http://www.springframework.org/schema/beans"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"XMLNS:AOP= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP"Xmlns:context= "Http://www.springframework.org/schema/context"Xmlns:tx= "Http://www.springframework.org/schema/tx"xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-3.1.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/ Spring-aop-3.1.xsd Http://www.springframework.org/schema/context http://www.springframework.org/schema/context/ Spring-context-3.1.xsd Http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/ Spring-tx-3.1.xsd ">    <Aop:aspectj-autoproxy></Aop:aspectj-autoproxy>    <Beanclass= "Org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator" />    <BeanID= "Aspectbean"class= "Com.spring.aop.TestAnnotationAspect" />    <BeanID= "Aservice"class= "Com.spring.service.AServiceImpl"></Bean>    <BeanID= "Bservice"class= "Com.spring.service.BServiceImpl"></Bean></Beans>

With regard to pointcut expressions, you need to practice well in order to understand the meaning in depth. Even if you understand, but it is very troublesome to write, and not as simple as imagined.

Finally, let us know:

Any notification (Advice) method can define the first parameter as a org.aspectj.lang.JoinPoint type. The joinpoint interface provides a number of useful methods, such as Getargs () (return method parameters), Getthis () (Return proxy object), Gettarget () (return target), Getsignature () (Returns information about the method being notified) and toString (), which prints out useful information about the method being notified.

The Signature object returned by Getsignature () can be cast to Methodsignature, which is powerful enough to get all the method information including the parameter name.

============ Friendship Link ============

Spring AOP Detailed Tutorial http://blog.csdn.net/wangpeng047/article/details/8556800

This article transferred from: http://blog.csdn.net/wangpeng047/article/details/8560694

Spring AOP Instances

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.