Spring Learning Notes (8) AOP Enhancement (advice) configuration and application __spring

Source: Internet
Author: User
Tags aop getmessage throwable
Enhanced Type

Enhancements (advice) are mainly comprised of the following five types
1. Predecessor Enhancement (beforeadvice): Enforcing enhancements before the target method executes
2. Post-Enhancement (Afterreturningadvice): Implement enhancements after the target method is implemented
3. Surround Enhancement (Mrthodinterceptor): Implement enhancements before and after the target method is performed
4. Exception throwing Enhancement (Throwsadvice): Enforcing enhancements after the target method throws an exception
5. Introduction Enhancement (Introductionintercrptor): Add new methods and properties to the target class, predecessor enhancements and post enhanced configurations

The following example code is used to analyze the predecessor enhancements, and if you want to log them now, record what people are calling. The predecessor-enhanced configuration can be summed up in the following steps: 1. Configure the Agent interface:

Package TEST.AOP;

Public interface ITarget {
    string speak (string name);
}
2. Define the object being represented
Package TEST.AOP;
The proxy object public
class Target implements itarget{

    private static final String name = "Zenghao";
    @Override public
    String speak (Integer age) {
        System.out.println ("Hello I ' m" + Age + "years old");
        Return "I ' m return value";
    }
    public static String GetName () {return
        name;
    }
}
3. Configuration Enhancements
Package TEST.AOP;
Import Java.lang.reflect.Method;

Import Org.springframework.aop.MethodBeforeAdvice; public class Beforeadvice implements Methodbeforeadvice {/** * @param methods: Method of Target class * Args: Method of the target class in parameter * obj : Target Class Instance * */@Override public void before (method method, object[] args, Object target) throws Thr owable {if (target instanceof target) {System.out.println ("Forward Logging:" + (target) target). GetName () + "tune
       Using the "+ method.getname () +" method, the incoming parameter is: "+ args[0]);

}}/*------------------split Line---------------------/* Package TEST.AOP;

Import Java.lang.reflect.Method;
Import Org.springframework.aop.AfterReturningAdvice;

Import Org.springframework.aop.MethodBeforeAdvice; 
    public class Afteradvice implements Afterreturningadvice {/** * @param * returnvalue Return value * Method: Methods of the target class * Args: Target class method entry parameter * obj: Target class instance * */@Override public void afterreturning (Object returnvalue
      Method     Object[] args, Object target) throws Throwable {if (target instanceof target) {System.out.println ("
       Post-log record: "+ ((target) target). GetName () +" called "+ method.getname () +" method, the return value is: "+ returnvalue); }
   }

}
4. Configure Proxy objects Proxyfactorybean

Peoxyfactorybean is the Factorybean implementation class, and we know that Factorybean is responsible for initializing the bean, and Proxyfactorybean is responsible for creating proxy instances for other beans, by injecting the use of the

<!--Configure the proxy object--> <bean id= "Mytarget" class= "Test.aop.Target"/> <!--Configure predecessor Enhancements--&
Gt <bean id= "Mybeforeadvice" class= "Test.aop.BeforeAdvice"/> <!--configuration post enhanced--> <bean " Myafterreturnadvice "class=" Test.aop.AfterAdvice/> <!--Configuration proxy object--> <bean id= "Proxyfactorybean" Org.springframework.aop.framework.ProxyFactoryBean "> <!--Configure proxy interface set--> <property name=" proxyinterfaces
    "Value=" Test.aop.ITarget "/> <!--proxy target objects need to implement interfaces that can be set up by <list> tags to multiple--> <!--to weave notifications into proxy objects-->
                <property name= "Interceptornames" > <list> <idref bean= "Mybeforeadvice"/> <idref bean= "Myafterreturnadvice"/> </list> </property><!--Configuration implements the advice enhanced interface Bean, specified as bean name--> <property name= "TargetName" value= "Mytarget" ></property><!--Agent target object--> & Lt;/bean> 
5. Test
Package TEST.AOP;

Import Org.junit.Before;
Import Org.junit.Test;
Import Org.springframework.context.ApplicationContext;
Import Org.springframework.context.support.ClassPathXmlApplicationContext;

public class Testaop {

    private applicationcontext ac;
    @Before Public
    Void Setup () {
        ac = new Classpathxmlapplicationcontext ("Classpath:test/aop/aop.xml");
    }

    @Test public
    void Test () {
        ITarget itarget = (itarget) ac.getbean ("Proxyfactorybean");
        Itarget.speak ();
    }

Test print:

Predecessor logging: Zenghao called the Speak method, passing in the parameter: 21
Hello I ' m years old
Post-logging: Zenghao called the Speak method, and the return value is: I ' m returns ' value surround enhanced configuration

On the previous basis, we added the surround enhancement class:

Package TEST.AOP;

Import Org.aopalliance.intercept.MethodInterceptor;
Import org.aopalliance.intercept.MethodInvocation;

public class Aroundadvice implements Methodinterceptor {

    @Override public
    Object Invoke (methodinvocation Invocation) throws Throwable {
        System.out.println (invocation.getarguments () [0] + "--" +
        Invocation.getstaticpart () + "--" +
        invocation.getthis (). GetClass () + "--" +
        Invocation.getmethod (). GetName ( ));
        Invocation.proceed ();//Reflection Calls target object method
        System.out.println ("Wrapping enhancement Call End");
        Return "I ' m around return value";
    }

In Aop.xml, similar to the predecessor-enhanced surround-enhanced configuration, run the test method and get the results:

Predecessor logging: Zenghao called the Speak method, passing in the parameter: 21
21--public abstract java.lang.String test.aop.ITarget.speak (java.lang.Integer)--class Test.aop.target--speak
Hello I ' m years old
Wrapping Enhancement Call End
Post-logging: Zenghao called the Speak method and returned the value: I ' m around return value
As we can see from the above, when using surround enhancement and back-and-forth enhancements, their execution order is abnormally enhanced configuration

Common scenarios for the configuration of the physical manager, when the method of database operation is abnormal, can be enhanced by the exception capture, error rollback and other operations. An instance that throws an exception enhancement looks like this:

Package TEST.AOP;

Import Java.lang.reflect.Method;
Import java.sql.SQLException;

Import Org.springframework.aop.ThrowsAdvice;

public class Exceptionadvice implements Throwsadvice {public
    void afterthrowing (SQLException e) {
        System.out.println (E.getmessage ());
    }
    public void afterthrowing (RuntimeException e) {
        System.out.println (e.getmessage ());
    }
    public void Afterthrowing (method method, object[] args, Object target,sqlexception e) {
        System.out.println ( E.getmessage ());
    }

There are several points to be noted:
1. The method name must be: afterthrowing
2. Three reference method method, object[] args, Object target is either provided together or not, and the last entry must be Throwable or its subclasses. When the target object throws an exception, the enhancement invokes a method that matches the highest similarity to the exception class (the closer the two classes are in the class's inheritance tree, the higher the similarity)

As for the introduction enhancement, it can dynamically add new interfaces or methods to the class, with unimaginable dynamic characteristics, which we will refer to separately in the later learning.

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.