Examples of 5 enhancement methods for "Spring" AOP

Source: Internet
Author: User
Tags throw exception throwable

Lin Bingwen Evankaka Original works. Reprint please specify the source Http://blog.csdn.net/evankaka

Spring AOP provides 5 types of notifications, namely before Advice (pre-notification), after returning Advice (post-notification), interception Around Advice (ambient notification), Throws Ad Vice (exception notification) and Introduction Advice (referral notification). The following are described separately.

1. Pre-notification (front-mounted enhancement)

The as implies notification is intended to weave before the method call. We can do this through spring's Methodbeforeadvice interface. Methodbeforeadvice only provides method before (), which has no return value, and the method accepts the 3 parameters of the calling method, the method parameter, and the target object. It is important to note that although the before () method gets the parameters of the calling method, it is worth noting that the method parameters can be changed!

Create a worker interface class:

/**  * Functional Worker Interface class * Author Lin Bingwen ([email protected] Blog: Http://blog.csdn.net/evankaka)  * Time 2015.4.22 */package Com.mucfc.advice;public interface Worker {void GetTool (string tool), void digsomething (string type); void Initwork ();}

Worker implementation class:

/**  * Functional Worker Implementation class * Author Lin Bingwen ([email protected] Blog: Http://blog.csdn.net/evankaka)  * Time 2015.4.22 */package Com.mucfc.advice;import Javax.management.runtimeerrorexception;public class Digworker implements Worker{@ overridepublic void GetTool (String tool) {     System.out.println ("---------------call Method--------------");     System.out.println ("collection Tool:" +tool);    throw new RuntimeException ("Run Exception"); @Overridepublic void digsomething (String type) {     System.out.println ("---------------call Method--------------"); System.out.println ("Start digging Hard:" +type);} @Overridepublic void Initwork () {System.out.println ("Generate a Digworker instance");}}

3, the method of creating the predecessor enhancement:

/**  * Function Pre-enhancement method * Author Lin Bingwen ([email protected] Blog: Http://blog.csdn.net/evankaka)  * Time 2015.4.22 */package Com.mucfc.advice;import Java.lang.reflect.method;import Org.springframework.aop.methodbeforeadvice;public Class Wearingbeforeadvice implements Methodbeforeadvice{public void before (Method arg0, object[] arg1, Object arg2) throws Throwable {string thing= (string) arg1[0]; System.out.println ("--------------for pre-Enhancement---------------"); System.out.println ("Get the +thing+" before you put on the overalls!! ");}}

4. Weave the enhancement method into the appropriate place
    1, do not use XML configuration instantiation    Worker target=new digworker ();        Beforeadvice advice=new Wearingbeforeadvice ();    Spring provides the agent factory    proxyfactory pfactory=new proxyfactory ();    Set the proxy target, using cglib dynamic proxy    pfactory.settarget (target) by default;        Add a predecessor enhancement to the proxy target, which will increase the enhancement    pfactory.addadvice (advice) for each method of the target;    Generate agent Instance    worker proxy= (worker) Pfactory.getproxy ();    Proxy.gettool ("drilling rig");    Proxy.digsomething ("Coal");

Result: Pre-enhancements were made before the two method invocations of the worker implementation class


The interface proxy is using the JDK dynamic proxy by default, such as to use Cglib dynamic code, plus:

    Specifies that optimizations are made, and Cglib dynamic    pfactory.setoptimize (true) will be used;

To use the JDK dynamic agent, add:

    Specifies that the interface is proxied via the JDK dynamic Agent    pfactory.setinterfaces (Target.getclass (). Getinterfaces ());
Second, post-enhancement

Post notification (after returning advice): A notification that is executed after a connection point is completed normally: for example, a method does not throw any exceptions and returns normally.

1, enhance the method agent

/**  * Function Post Enhancement method * Author Lin Bingwen ([email protected] Blog: Http://blog.csdn.net/evankaka)  * Time 2015.4.22 */package Com.mucfc.advice;import Java.lang.reflect.method;import Org.springframework.aop.afterreturningadvice;public Class Weaningafteradvice implements afterreturningadvice{@Overridepublic void afterreturning (Object arg0, Method arg1, Object[] Arg2,object arg3) throws Throwable {System.out.println ("--------------for post-Enhancement---------------"); System.out.println ("Work is over, please take off your overalls First");}}
The workers or the workers above, the other methods are the same.

2, we can use the API function directly when we make the enhanced configuration, but it is more complicated, let us use XML annotation configuration method to implement both pre-and post-post enhancements

Create a new XML file under the SRC folder named Beans.xml

The previous sections are as follows:

<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans" xmlns: Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:p= "http://www.springframework.org/schema/p" xmlns:context= "Http://www.springframework.org/schema/context" xsi:schemalocation= "Http://www.springframework.org/schema/beans                  http://www.springframework.org/schema/beans/spring-beans-3.0.xsd          http://www.springframework.org/ Schema/context          http://www.springframework.org/schema/context/spring-context-3.0.xsd ">

Then there is the following configuration:

        <!--to enhance the target--><bean id= "target" class= "Com.mucfc.advice.DigWorker" init-method= "Initwork"/>            < !--Pre-enhancement method--><bean id= "Beforeadvice" class= "Com.mucfc.advice.WearingBeforeAdvice"/><!--post-enhancement Method-- <bean id= "Afteradvice" class= "Com.mucfc.advice.WeaningAfterAdvice"/><!--set up both pre-and post-enhancement methods  -->< Bean id= "Worker1" class= "Org.springframework.aop.framework.ProxyFactoryBean" p:proxyinterfaces= " Com.mucfc.advice.Worker "p:interceptornames=" Beforeadvice,afteradvice "p:target-ref=" target "lazy-init=" true "/ >
The p:interceptornames= "Beforeadvice,afteradvice" here means that both the front and back enhancements are added.

Lazy-init= "True" indicates that the instance is initialized when it can be used

3. Call

   2. Instantiate   ApplicationContext ctx=new classpathxmlapplicationcontext ("Beans.xml") using Spring's XML configuration.   Worker1 with front and rear enhanced   worker worker1= (worker) Ctx.getbean ("Worker1");   System.out.println ("Worker1 into work:");   Worker1.gettool ("hoe");
The results are as follows:


Pre-and post-build enhancements have been made before calling the method, and note that this will weave the enhancements for all the methods of the worker Class!


Third, surround enhancement

Surround notification (Around Advice): A notification that surrounds a connection point, such as a method call. This is the most powerful type of notification. Surround notifications can accomplish custom behavior before and after a method call. It also chooses whether to continue execution of the connection point or to return its own return value directly or throw an exception to end the execution.


1. Add the Enhancement method class:

/**  * Feature Wrapping Enhancement method * Author Lin Bingwen ([email protected] Blog: Http://blog.csdn.net/evankaka)  * Time 2015.4.22 */package Com.mucfc.advice;import Java.lang.reflect.method;import Org.aopalliance.intercept.methodinterceptor;import Org.aopalliance.intercept.MethodInvocation;; Public  class Wearinginterceptor implements methodinterceptor{@Overridepublic Object invoke (Methodinvocation arg0 ) throws Throwable {object[] args=arg0.getarguments ();//target method into parameter String toolname= (string) args[0]; System.out.println ("--------------Surround enhancement Start---------------"); System.out.println ("Get" +toolname+ "before putting on overalls"); Object object=arg0.proceed (); System.out.println ("Work is over, please take off your overalls first"); System.out.println ("--------------Surround Enhancement End---------------");; return object;}}
2, then or in the Beans.xml configuration:

        <!--surround Enhancement method--><bean id= "Aroundadvice" class= "Com.mucfc.advice.WearingInterceptor"/><!--set Surround enhancement method  --><bean id= "Worker2" class= "Org.springframework.aop.framework.ProxyFactoryBean" p:proxyinterfaces= " Com.mucfc.advice.Worker "p:interceptornames=" Aroundadvice "p:target-ref=" target "lazy-init=" true "/>

3. Use

   Work2 with surround   -enhanced worker worker2= (worker) Ctx.getbean ("Worker2");   System.out.println ("Worker2 into work:");   Worker2.gettool ("drilling rig");

Results:

Third, exception throw enhancement

Exception notification (after throwing advice): A notification that is executed when a method throws an exception exits.

1, the method of the predecessor enhancement method of the workers to add a class, throw new RuntimeException ("Run Exception");

@Overridepublic void GetTool (String tool) {     System.out.println ("---------------call Method--------------");     System.out.println ("collection Tool:" +tool);     throw new RuntimeException ("Run Exception");

2. Handling Exceptions Thrown classes

/**  * Feature exception throw enhancement class * author Lin Bingwen ([email protected] Blog: Http://blog.csdn.net/evankaka)  * Time 2015.4.22 */package Com.mucfc.advice;import Java.lang.reflect.method;import Org.springframework.aop.throwsadvice;public Class Weaningthrowadvice implements Throwsadvice {public void afterthrowing (method, object[] args, Object target, Exception ex) throws Throwable {    System.out.println ("--------------------");    System.out.println ("Method:" +method.getname ());    System.out.println ("Throw exception" +ex.getmessage ());    SYSTEM.OUT.PRINTLN ("ROLLBACK transaction successfully");}}

3. XML configuration

<!--exception Throw enhanced method  --><bean id= "Thorwadvice" class= "Com.mucfc.advice.WeaningThrowAdvice"/><!-- Set exception throw enhancement method  proxytargetclass= "True", use Cglib proxy--><bean id= "Worker3" class= " Org.springframework.aop.framework.ProxyFactoryBean "p:interceptornames=" Thorwadvice "p:target-ref=" target "P: Proxytargetclass= "true"/>

4. Use

   Work3 with surround  -enhanced worker worker3= (worker) Ctx.getbean ("Worker3");   System.out.println ("Worker3 into work:");   Worker3.gettool ("Hammer");

Note that because the method is forced to throw an exception, so to run the above code, remember to the previous enhancement method test code is removed, leaving only the following code:

V. Introduction and enhancement

The introduction enhancement is a kind of special enhancement type, it does not weave the enhancement around the target method, but creates new methods and properties for the target class, so the connection point of the interface enhancement is class-level, not method-level. With the introduction enhancement, we can add an interface implementation for the target class, that is, the original target class does not implement an interface, through the introduction of the enhancement can create a proxy for the target class to implement the interface. Generally used relatively little, here will not write code

Lin Bingwen Evankaka Original works. Reprint please specify the source Http://blog.csdn.net/evankaka

Examples of 5 enhancement methods for "Spring" AOP

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.