SPRINGAOP using extensions

Source: Internet
Author: User
Tags throwable

In "Spring First" we learned that spring supports AOP and that the configurable method has a pre-safeguarded and post-strong, but spring supports a variety of previously strong types. Here are some examples of some of the most commonly used safeguarded in spring (pre-enhancement and post-placement are no longer introduced, see the "First Spring" blog for details).

Exception throw safeguarded

Exception throwing has been strongly characterized when the target method throws an exception when the weaving was strong processing. First we write a class that implements the exception-strong code, and implements the Throwsadvice interface for the class. As shown below:

 PackageCN.WZ.AOP;ImportJava.lang.reflect.Method;ImportOrg.apache.log4j.Logger;ImportOrg.springframework.aop.ThrowsAdvice; Public classErrorloggerImplementsThrowsadvice {Logger log=logger.getlogger (Errorlogger.class); /*** Methods of implementing the exception-strong code *@parammethod Target Methods name *@paramargs incoming parameters to the target method *@paraminstance of the class in which the target method resides *@paramthe exception object thrown in the E-target method*/     Public voidafterthrowing (Method method,object[] Args,object target,exception e) {log.error (Method.getname ()+ "Exception occurred:" +e); }}

The above code was strong by implementing the Throwsadvice interface implementation exception, where no method is defined in the Throwsadvice interface, but we must adhere to the following method signature when defining the safeguarded method thrown by the exception:

void Afterthrowing ([Method method,object [] Arguments,object target,]throwable ex)

Here spring specifies that the method name must be "afterthrowing". Only the last parameter of the method parameter is required, the first three parameters are optional, but the first three parameters can only be provided or not provided! Otherwise, it is not possible to achieve a strong. Write the test class below to test:

 Packagecn.wz.test;ImportOrg.springframework.context.ApplicationContext;ImportOrg.springframework.context.support.ClassPathXmlApplicationContext; Public classExceptiontest { Public Static voidMain (string[] args)throwsException {ApplicationContext context=NewClasspathxmlapplicationcontext ("Applicationcontext.xml"); Exceptiontest Bean= Context.getbean ("Test", exceptiontest.class);    Bean.add (); }     Public voidAdd ()throwsException {Throw NewException ("Error"); }}

Final Run Result:

The configuration method for the spring configuration file is the same as the predecessor enhancement and the post-strong configuration method, which is no longer shown here,

Surround safeguarded

Surround safeguarded can be woven before and after the target method has been strong processing. Surround enhancement is the most powerful enhancement, and spring gives all the control over the target method to it. In wrapping safeguarded processing, you can get or modify the parameters of the target method, return the value, you can treat it with exception, and even decide whether the target method executes!

Okay, here's a look at how to implement surround safeguarded. The first thing to do is to define a class that implements surround-strong code, which implements the Invoke () method of the Methodinterceptor interface and writes the safeguarded code in the Invoke () method.

 PackageCN.WZ.AOP;ImportJava.lang.reflect.Method;Importjava.util.Arrays;ImportOrg.aopalliance.intercept.MethodInterceptor;Importorg.aopalliance.intercept.MethodInvocation;ImportOrg.apache.log4j.Logger; Public classErrorloggerImplementsmethodinterceptor {Logger log=logger.getlogger (Errorlogger.class);  PublicObject Invoke (Methodinvocation arg0)throwsThrowable {Method Method=Arg0.getmethod (); object[] Arguments=arg0.getarguments (); Object Target=Arg0.getthis (); Log.info ("+method.getname () +" method called "+target+". Method Entry: "+arrays.tostring (arguments)); Try{Object result=arg0.proceed (); Log.info ("+method.getname () +" method called "+target+". Method return Value: "+result); returnresult; } Catch(Exception e) {log.error (Method.getname ()+ "Method Exception:" +e); }         return NULL; }}

The above code implements surround enhancement through the Methodinterceptor interface. This interface requires the implementation of the Invoke method, whose parameter methodinvocation not only mad at the target method and into the parameter group, but also encapsulated the target object of the agent. The method of the target object response can be called by the proceed method to achieve full control of the target method. The results of the test run with an exception thrown by the strong test code are as follows:

Implementing safeguarded with annotations

In addition to implementing the specific interfaces provided by spring, spring also enables the use of integrated ASPECTJ to define enhanced classes in annotations. Greatly reduces the amount of work in the configuration file.

Note: Using ASPECTJ is to ensure that the JDK version is version 5.0 or later, otherwise it will not be possible to use annotation technology, followed by the introduction of the ASM module's jar package into the project

Pre-safeguarded and post-strong classes:
 PackageCN.WZ.AOP;ImportOrg.apache.log4j.Logger;Importorg.aspectj.lang.annotation.AfterReturning;ImportOrg.aspectj.lang.annotation.Aspect;ImportOrg.aspectj.lang.annotation.Before; @Aspect Public classUserlogger {Private Static FinalLogger Log=logger.getlogger (Userlogger.class); @Before ("Execution (public void Add ())")     Public voidbefore () {Log.info ("Front Enhancements"); } @AfterReturning ("Execution (public void Add ())")     Public voidafterreturning () {Log.info ("Post Enhancement"); }}

The configuration in the spring configuration file is as follows:

Exception throw Enhancement class:
 PackageCN.WZ.AOP;ImportOrg.apache.log4j.Logger;ImportOrg.aspectj.lang.JoinPoint;Importorg.aspectj.lang.annotation.AfterThrowing;Importorg.aspectj.lang.annotation.Aspect; @Aspect Public classError_logger {Private Static FinalLogger Log=logger.getlogger (Userlogger.class); @AfterThrowing (Pointcut= "Execution (public void Add ())", throwing= "E")     Public voidagterthrowing (Joinpoint jp,exception e) {log.error (Jp.getsignature (). GetName ()+ "Exception occurred:" +e); }}
Surround Enhancement Classes:
 PackageCN.WZ.AOP;ImportOrg.apache.log4j.Logger;ImportOrg.aspectj.lang.ProceedingJoinPoint;ImportOrg.aspectj.lang.annotation.Around;Importorg.aspectj.lang.annotation.Aspect; @Aspect Public classArounslogger {Private Static FinalLogger Log=logger.getlogger (Userlogger.class); @Around ("Execution (public void Add ())")     PublicObject Aroundlogger (proceedingjoinpoint JP)throwsthrowable{System.out.println ("Front Enhancements"); Object obj= Jp.proceed ();//call the original methodSystem.out.println ("Post enhancement"); returnobj; }}

SPRINGAOP using extensions

Related Article

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.