Spring Beginner's annotation implements AOP pre-notification, post-notification, return notification, and exception notification.

Source: Internet
Author: User
Tags mul

Implements the subtraction of two integers, printing the log before each method is executed.

Arithmeticcalculator.java:

 Package Spring.aop.impl;  Public Interface arithmeticcalculator {        int Add ( int i,int  j);     int Sub (int i,int  j);     int mul (int i,int  j);     int div ( int i,int  j);    }

Arithmeticcalculatorimpl.java:

 PackageSpring.aop.impl;Importorg.springframework.stereotype.Component; @Component ("Arithmeticcalculator") Public classArithmeticcalculatorimplImplementsArithmeticcalculator { Public intAddintIintj) {intresult = i+J; returnresult; }     Public intSubintIintj) {intresult = IJ; returnresult; }     Public intMulintIintj) {intresult = i*J; returnresult; }     Public intDivintIintj) {intresult = i/J; returnresult; }}

Loggingaspect.java:

 PackageSpring.aop.impl;Importjava.util.Arrays;Importjava.util.List;ImportOrg.aspectj.lang.JoinPoint;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;ImportOrg.springframework.core.annotation.Order;Importorg.springframework.stereotype.Component; @Order (1)//If you have multiple facets, you can use @order to specify the priority of the slice, and the lower the value the higher the priority@Aspect @component Public classLoggingaspect {/*** Define a method to define pointcut expressions, generally, this method does not add other code * How to use? * 1. If in this class, such as @before ("Declarejoinpointexpression ()"), refer directly to the method name * 2. In another package class or other class, such as @before (" Package name. Class name. Declarejoinpointexpression () ")*/@Pointcut ("Execution (public int spring.aop.impl.arithmeticcalculator.* (..))")     Public voiddeclarejoinpointexpression () {}/*** Execute a piece of code before each implementation class of the Spring.aop.impl.ArithmeticCalculator interface begins*/@Before ("Declarejoinpointexpression ()")     Public voidBeforemethod (Joinpoint joinpoint) {String methodName=joinpoint.getsignature (). GetName (); List<Object> args=arrays.aslist (Joinpoint.getargs ()); System.out.println ("The method" +methodname+ "begins" +args); }        /*** Execute after method (whether or not an exception is thrown) *@paramJoinpoint*/@After ("Execution (public int spring.aop.impl.arithmeticcalculator.* (..))")     Public voidAftermethod (Joinpoint joinpoint) {String methodName=joinpoint.getsignature (). GetName (); List<Object> args=arrays.aslist (Joinpoint.getargs ()); System.out.println ("The method" +methodname+ "ends"); }        /*** Notification after normal execution of the method * Returns a notification that the return value of the method can be accessed *@paramJoinpoint*/@AfterReturning (Value= "Execution (public int spring.aop.impl.arithmeticcalculator.* (..))", returning= "Result")     Public voidAfterreturnmethod (joinpoint joinpoint,object result) {String methodName=joinpoint.getsignature (). GetName (); System.out.println ("The method" +methodname+ "ends with afterreturning" +result); }        /*** Code that executes when the target method has an exception can access the exception information that appears, you can specify that when the specified exception occurs, the Execute * method parameter exception change to a different exception can be specified when the specified exception occurs *@paramJoinpoint *@paramex*/@AfterThrowing (Value= "Execution (public int spring.aop.impl.arithmeticcalculator.* (..))", throwing= "Ex")     Public  voidafterthrowing (Joinpoint joinpoint,exception ex) {String methodName=joinpoint.getsignature (). GetName (); System.out.println ("The method" +methodname+ "occurs exection:" +ex); }        /*** Surround Notifications * need to carry Proceedingjoinpoint type parameters * Similar to the whole process of dynamic agents: Proceedingjoinpoint type parameter can decide whether to execute the target method * Surround notification must have a return return value, which is the return value of the target method *@paramJoinpoint*/    /*@Around ("Execution (public int spring.aop.impl.arithmeticcalculator.* (..))")        public Object Aroundmethod (Proceedingjoinpoint joinpoint) {object result=null;        String methodname=joinpoint.getsignature (). GetName (); try {//Pre-notification System.out.println ("---->the method" +methodname+ "begins with" +arrays.aslist (JOINP            Oint.getargs ()));            Implementation of the Target method Result=joinpoint.proceed ();        Return notification System.out.println ("---->" +result);            } catch (Throwable e) {e.printstacktrace ();        Exception notification SYSTEM.OUT.PRINTLN ("---->" +e);        }//Post notification System.out.println ("---->the method" +methodname+ "ends");    return result; }    */}

Applicationcontext.xml:

<?XML version= "1.0" encoding= "UTF-8"?><Beansxmlns= "Http://www.springframework.org/schema/beans"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"xmlns:p= "http://www.springframework.org/schema/p"XMLNS:AOP= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP"Xmlns:context= "Http://www.springframework.org/schema/context"xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-4.1.xsd Http://www.springframework.org/schema/context Http://www.springframework.org/schema/context /spring-context-4.3.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/ Spring-aop-4.3.xsd ">        <!--Configure automatic scanning of packages -    <Context:component-scanBase-package= "Spring.aop.impl"></Context:component-scan>        <Aop:aspectj-autoproxy></Aop:aspectj-autoproxy></Beans>

Test:

 Packagespring.aop.impl.test;ImportOrg.springframework.context.ApplicationContext;ImportOrg.springframework.context.support.ClassPathXmlApplicationContext;ImportSpring.aop.impl.ArithmeticCalculator; Public classMain { Public Static voidMain (string[] args) {ApplicationContext ctx=NewClasspathxmlapplicationcontext ("Applicationcontext.xml"); Arithmeticcalculator Arithmeticcalculator= (arithmeticcalculator) ctx.getbean ("Arithmeticcalculator"); intResult=arithmeticcalculator.add (10, 20); System.out.println ("Result:" +result); Result=arithmeticcalculator.div (10, 0); System.out.println ("Result:" +result); }}

Output:

The method add begins [10, 20]the method Add ends the method add ends with Afterreturning30Result:30The method Div begins [10, 0]the Method Div ends the method div occurs exection:java.lang.ArithmeticException:/by zeroexception in thread"Main" java.lang.ArithmeticException:/by Zero at Spring.aop.impl.ArithmeticCalculatorImpl.div (Arithmeticcalculatorimpl.java:24) at Sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method) at Sun.reflect.NativeMethodAccessorImpl.invoke (Nativemethodaccessorimpl.java:62) at Sun.reflect.DelegatingMethodAccessorImpl.invoke (Delegatingmethodaccessorimpl.java:43) at Java.lang.reflect.Method.invoke (Method.java:497) at Org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection (Aoputils.java:333) at Org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint ( Reflectivemethodinvocation.java:190) at Org.springframework.aop.framework.ReflectiveMethodInvocation.proceed (Reflectivemethodinvocation.java: 157) at Org.springframework.aop.framework.adapter.MethodBeforeAdviceInterceptor.invoke ( Methodbeforeadviceinterceptor.java:52) at Org.springframework.aop.framework.ReflectiveMethodInvocation.proceed (Reflectivemethodinvocation.java: 179) at Org.springframework.aop.aspectj.AspectJAfterAdvice.invoke (Aspectjafteradvice.java:47) at Org.springframework.aop.framework.ReflectiveMethodInvocation.proceed (Reflectivemethodinvocation.java: 179) at Org.springframework.aop.framework.adapter.AfterReturningAdviceInterceptor.invoke ( Afterreturningadviceinterceptor.java:52) at Org.springframework.aop.framework.ReflectiveMethodInvocation.proceed (Reflectivemethodinvocation.java: 179) at Org.springframework.aop.aspectj.AspectJAfterThrowingAdvice.invoke (Aspectjafterthrowingadvice.java:62) at Org.springframework.aop.framework.ReflectiveMethodInvocation.proceed (Reflectivemethodinvocation.java: 179) at Org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke (Exposeinvocationinterceptor.java :92) at Org.springframework.aop.framework.ReflectiveMethodInvocation.proceed (Reflectivemethodinvocation.java: 179) at Org.springframework.aop.framework.JdkDynamicAopProxy.invoke (Jdkdynamicaopproxy.java:213At Com.sun.proxy. $Proxy 12.div (Unknown Source) at Spring.aop.impl.test.Main.main (Main.java:18)

Spring Beginner's annotation implements AOP pre-notification, post-notification, return notification, and exception notification.

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.