"Sping Secret" 14, @before @AfterThrowing

Source: Internet
Author: User

@before

Basic mode, we can first look directly on it, relatively simple, online a bunch of ...

It's not like I'm faking it, I've been studying for so long. Spring,aop's fur is the online blog content, a little bit more advanced I will not, here skip the basic part

However, it is important to understand one wave:

1. Test the intercepted method inside to invoke another interception method of the same kind

Note: This will only be intercepted once, and will not intercept the method inside the method called again, of course, you directly in the periphery of the call another method, or will be intercepted

2, test the intercepted method inside call another different class interception method

Note: This will be intercepted two times, you call this method will be intercepted once, you call this method inside the method called, will be intercepted once

These two questions have a major premise, all mentioned methods are intercepted objects, that is, the Pointcut contains the method used above

OK, finish up, okay, here's the point.

We want to know what the parameters of the intercepted method are, what are we going to do with it?

Here's a question, let's fix it.

Here we introduce the joinpoint and args, the former can be obtained by the Getargs method of parameters, there are other other methods used. The latter is a marker inside the annotation and can be directly declared with the corresponding parameter

We build a bean

 PackageCn.cutter.start.bean;ImportOrg.apache.commons.logging.Log;Importorg.apache.commons.logging.LogFactory;Importorg.springframework.stereotype.Component; @Component Public classBeofretestbean {Private Static FinalLog logger = Logfactory.getlog (Beofretestbean.class);  Public voidmethod1 () {Logger.info ("Here's the method method1."); }         Public voidmethod2 (String param1) {logger.info ("Here is the method method2 parameter value is: param1-" +param1); }    }

Create an intercept class to intercept this bean

 PackageCN.CUTTER.START.AOP;ImportJava.lang.reflect.Modifier;ImportOrg.apache.commons.logging.Log;Importorg.apache.commons.logging.LogFactory;ImportOrg.aspectj.lang.JoinPoint;ImportOrg.aspectj.lang.annotation.Aspect;ImportOrg.aspectj.lang.annotation.Before;ImportOrg.aspectj.lang.annotation.Pointcut;Importorg.springframework.stereotype.Component, @Component @aspect Public classBeforeaspect {Private Static FinalLog logger = Logfactory.getlog (beforeaspect.class); @Pointcut ("Execution (* cn.cutter.start.bean.beofretestbean.* (..))")    Private voidbeforepointcut () {}/*** Direct Front intercept*/@Before ("Beforepointcut ()")     Public voidBeforeopertatornoarg () {Logger.info ("Front intercept without parameter Beforeopertatornoarg"); } @Before ("Beforepointcut ()")     Public voidbeforeopertatorwithjoinpoint (Joinpoint joinpoint) {logger.info ("Front intercept with parameter Beforeopertatorwithjoinpoint"); Logger.info (The target method name is: "+joinpoint.getsignature (). GetName ()); Logger.info ("Simple class name of the class to which the target method belongs:" +joinpoint.getsignature (). Getdeclaringtype (). Getsimplename ()); Logger.info ("Class name of the class to which the target method belongs:" +joinpoint.getsignature (). Getdeclaringtypename ()); Logger.info ("Target method declaration type:" +modifier.tostring (Joinpoint.getsignature (). getmodifiers ())); //gets the parameters of the incoming target methodobject[] args =Joinpoint.getargs ();  for(inti = 0; i < args.length; i++) {Logger.info ("First" + (i+1) + "parameters are:" +Args[i]); } logger.info ("Object to be proxied:" +joinpoint.gettarget ()); Logger.info ("Proxy object itself:" +joinpoint.getthis ()); } @Before ("Beforepointcut () && args (param1)")     Public voidBeforeopertatorwitharg (String param1) {logger.info ("The pre-intercept band parameter Beforeopertatorwitharg parameter is param1:" +param1); } @Before ("Beforepointcut () && args (param1)")     Public voidBeforeopertatorwithargandjoinpoint (Joinpoint joinpoint, String param1) {logger.info ("------------------------------------------------------------------------"); Logger.info ("The pre-intercept band parameter Beforeopertatorwithargandjoinpoint parameter is param1:" +param1); Logger.info (The target method name is: "+joinpoint.getsignature (). GetName ()); Logger.info ("Simple class name of the class to which the target method belongs:" +joinpoint.getsignature (). Getdeclaringtype (). Getsimplename ()); Logger.info ("Class name of the class to which the target method belongs:" +joinpoint.getsignature (). Getdeclaringtypename ()); Logger.info ("Target method declaration type:" +modifier.tostring (Joinpoint.getsignature (). getmodifiers ())); //gets the parameters of the incoming target methodobject[] args =Joinpoint.getargs ();  for(inti = 0; i < args.length; i++) {Logger.info ("First" + (i+1) + "parameters are:" +Args[i]); } logger.info ("Object to be proxied:" +joinpoint.gettarget ()); Logger.info ("Proxy object itself:" +joinpoint.getthis ()); Logger.info ("------------------------------------------------------------------------"); }    }

View results:

    @Test    publicvoid  testAop2 () {        this. Before ();                 = (Beofretestbean) ctx.getbean ("Beofretestbean");         //         btb.method1 ();        BTB.METHOD2 ("Testing AOP before");            }

Results:

@AfterThrowing

This annotation has a unique attribute, that is throwing

Design a class that throws an exception after executing a method

 PackageCn.cutter.start.bean;ImportOrg.apache.commons.logging.Log;Importorg.apache.commons.logging.LogFactory;Importorg.springframework.stereotype.Component; @Component Public classAfterthrowingtestbean {Private Static FinalLog logger = Logfactory.getlog (Afterthrowingtestbean.class);  Public voidThrowingexception ()throwsException {Throw NewException ("Test exception thrown"); }    }

Design Interception class

 PackageCN.CUTTER.START.AOP;ImportOrg.apache.commons.logging.Log;Importorg.apache.commons.logging.LogFactory;Importorg.aspectj.lang.annotation.AfterThrowing;ImportOrg.aspectj.lang.annotation.Aspect;Importorg.springframework.stereotype.Component, @Component @aspect Public classAfterthrowingaspect {Private Static FinalLog logger = Logfactory.getlog (afterthrowingaspect.class); @AfterThrowing (Pointcut= "Execution (* cn.cutter.start.bean.afterthrowingtestbean.* (..))", throwing= "E")     Public voidtestafterthrowing (Exception e) {logger.info ("Testafterthrowing:" +e.getmessage ());            E.printstacktrace (); }    }

Test results:

@Test      Public void testAop3 () {        this. Before ();                 = (Afterthrowingtestbean) ctx.getbean ("Afterthrowingtestbean");                 Try {            att.throwingexception ();         Catch (Exception e) {            //  TODO auto-generated catch block            System.out.println (" Throw exception Catch ");        }            }

Results:

Sping Revelation 14, @before @AfterThrowing

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.