Introduction to Spring AOP configuration using examples and implementation procedures and principles

Source: Internet
Author: User
Tags aop exception handling throwable xmlns stringbuffer

I believe that as long as the use of Spring framework, we are not unfamiliar with AOP, especially to mention it can be immediately casually said, generally used in log processing, exception handling, authorization and other aspects. Today's example illustrates the use of Spring AOP configuration (note that it is not ASPECTJ configuration usage) and the general implementation process and principles of spring AOP through source code.

first, related concepts Jointpoint

Before the system runs, the functional modules of AOP need to be woven into the functional modules of OOP. For this weaving process, it is necessary to know which functional points of the system are weaving operations, and the system function points that will be woven into them are called jointpoint. In spring AOP, a connection point always represents the execution of a method, such as when a method is called or when an exception is handled. Several types of joinpoint are common:

Ø method Invocation: The point at which the program executes when a method is called;

Ø method Execution: This type represents the point at which a method's internal execution begins, and should be distinguished from the method invocation;

Ø Construction Method Invocation: The point at which an object is called when its construction method is initialized during program execution;

Ø construction Method Execution: It is the relationship between the method invocation and the execution of the method, as the constructor method calls;

Ø field Settings: An object's properties are set by setter method or directly set by the execution point;

Ø Field acquisition: The execution point where the corresponding property of an object is accessed;

Ø exception handling execution: After certain types of exceptions are thrown, corresponding exception handling logic execution points;

Ø class initialization: The execution point at which certain static types or static blocks of a class are initialized. Pointcut

Pointcut represents the joinpoint of the expression, simple and easy to understand that is Joinpoint collection. In the process of weaving crosscutting logic into the current system, you need an expression method, although you know which feature points you need to weave into the functional modules of AOP. Pointcut is associated with a pointcut expression and runs on the joinpoint that satisfy the pointcut. There are several pointcut methods that are commonly used today:

Ø directly specify the method name where the Joinpoint is located;

Ø Regular Expressions, spring's AOP supports this approach;

Ø using a specific pointcut language, Spring 2.0 supports this approach. Advice

Advice is the carrier of the single crosscutting concern logic, which represents the crosscutting logic that will be woven into the joinpoint. The logic that executes on a particular connection point in a slice. Depending on the difference in timing of the execution of the Joinpoint location or the completion function, it can be divided into the following forms:

Øbefore Advice: The type of Advice executed before joinpoint the specified position can be used to do some initialization work of the system, such as setting the system initial value, obtaining the necessary system resources, etc.

Øafter Advice: The type of Advice executed after the corresponding connection point, it can also be subdivided into the following three types:

²after returning Advice: It will only execute if the current execution of the joinpoint is completed properly;

²after throwing Advice: Executes when an exception is thrown during the current joinpoint execution;

²after Advice: This type of Advice executes regardless of whether the execution process at Joinpoint is normal or throws an exception.

Øaround Advice: Wrapping the Joinpoint attached to it, you can specify the appropriate logic before and after joinpoint, or even interrupt or ignore the execution of the original program flow at Joinpoint. Aspect

It is an AOP conceptual entity that encapsulates the cross-cutting concern logic in a system in a modular package, which can contain multiple pointcut and related advice definitions. Weave Weaving Device

After the weaving process, the aspect modular crosscutting concerns are integrated into the existing system of OOP, and the completion of the weaving process entity is called the Loom. Spring uses a set of classes to complete the final weaving operation, and the Proxyfactory class is the most common type of Spring AOP Weaver. Target target Object

Conforming to the conditions specified by Pointcut, the object that is woven into the crosscutting logic during the weaving process is called the target object.

Looking at the concepts above, you may feel a little dazzled by the fact that a simple example of AOP can help us quickly understand its internal mechanisms. In fact, the method of interception has different implementations, commonly used is directly using spring provides a variety of advice interception, the other is the use of Methodinterceptor way to intercept.

Ii. Examples of configuration use

Spring-Provided advice interception method

Define a logical interface Ibusinesslogic:

Package COM.WOW.ASC.AOP;

Public interface Ibusinesslogic {public

    void foo ();

    public void Bar () throws businesslogicexception;
    
    Public long time ();
}
There is an businesslogicexception exception, which is used for an instance that is later examined for Throwsadvice, which is defined as:

Package COM.WOW.ASC.AOP;

public class Businesslogicexception extends Exception {

}

For the implementation of the business logic Businesslogic, as follows:
Package COM.WOW.ASC.AOP;

public class Businesslogic implements Ibusinesslogic {
    @Override public
    void foo () {
        System.out.println (" Inside Businesslogic.foo () ");
    }
    @Override public
    void Bar () throws Businesslogicexception {
        System.out.println ("Inside Businesslogic.bar ()") ;
        throw new Businesslogicexception ();
    }
     / 
     * Returns the time that the method was executed
     *
    /@Override public
    Long () {
        System.out.println ("Inside Businesslogic.time () ");
        Long startTime = System.currenttimemillis ();
        for (int i = 0; i < 100000000; i++);
        Long endTime = System.currenttimemillis ();
        
        return (endtime-starttime);
    }
}

After the business logic code is completed, more cross-cutting insertion points are designed, such as handling various processes before or after the method executes, or when the exception is thrown. The notation for advice is as follows:

Package COM.WOW.ASC.AOP;
Import Java.lang.reflect.Method;
Import Org.springframework.aop.MethodBeforeAdvice;  /* * Represents a advice */public class Tracingbeforeadvice implements Methodbeforeadvice {@Override public) that is intercepted before the method executes void before (method, object[] args, Object target) throws Throwable {System.out.println ("Execute before (b
    Y "+ method.getdeclaringclass (). GetName () +". "+ method.getname () +") ";

}} package COM.WOW.ASC.AOP;
Import Java.lang.reflect.Method;
Import Org.springframework.aop.AfterReturningAdvice; /* * Indicates a advice */public class Tracingafteradvice implements Afterreturningadvice {@Override Public when method is returned void Afterreturning (Object returnvalue, method, object[] args, object target) throws Throwable {System.out
        . println (Method.getdeclaringclass (). GetName () + "." + method.getname () + "spend time:" + returnvalue); System.out.println ("Execute after" + Method.getdeclaringclass (). GetName () + "." + method. GetName () + ")");

}} package COM.WOW.ASC.AOP;
Import Java.lang.reflect.Method;
Import Org.springframework.aop.ThrowsAdvice; /* * Indicates an exception is thrown when advice */public class Tracingthrowsadvice implements Throwsadvice {public void Afterthrowin G (method, object[] args, Object target, Throwable subclass) {System.out.println ("Logging that a" + SUBC
      Lass + "Exception was thrown.");
 }
}

After designing the code and logic described above, you can combine the above classes by Applicationcontext.xml, and in the assembly process you will be able to identify which methods of the class need to be intercepted and what will be done before and after interception. Examples of specific configurations:

<?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:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xmlns:tx= " Http://www.springframework.org/schema/tx "xmlns:context=" Http://www.springframework.org/schema/context "xsi: schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-2.5.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/ Spring-aop-2.5.xsd Http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2 .5.xsd Http://www.springframework.org/schema/context Http://localhost:8080/schema/www.springframework.org/schema /context/spring-context-2.5.xsd "> <bean id=" businesslogic "class=" Com.wow.asc.aop.BusinessLogic "/> <
	Bean id= "Businesslogicbean" class= "Org.springframework.aop.framework.ProxyFactoryBean" >	<property name= "Proxyinterfaces" > <value>com.wow.asc.aop.IBusinessLogic</value> </property > <property name= "target" > <ref local= "businesslogic"/> </property> <property name= "inte Rceptornames "> <list> <value>theTracingBeforeAdvisor</value> <value>the Tracingafteradvisor</value> <value>theTracingThrowsAdvisor</value> </list> & lt;/property> </bean> <bean id= "Thetracingbeforeadvisor" class= " Org.springframework.aop.support.RegexpMethodPointcutAdvisor "> <property name=" Advice "> <ref local=
		"Thetracingbeforeadvice"/> </property> <property name= "pattern" > <value>.*</value> </property> </bean> <bean id= "Thetracingafteradvisor" class= " Org.springframework.aop.support.RegexpMethodPointcutAdvisor "> <property name=" Advice "> <ref locaL= "Thetracingafteradvice"/> </property> <property name= "pattern" > &LT;VALUE&GT;.*TIME.*&LT;/VALUE&G
		T </property> </bean> <bean id= "Thetracingthrowsadvisor" class= " Org.springframework.aop.support.RegexpMethodPointcutAdvisor "> <property name=" Advice "> <ref local="
		Thetracingthrowsadvice "/> </property> <property name=" pattern "> <value>.*bar.*</value> </property> </bean> <bean id= "Thetracingbeforeadvice" class= "Com.wow.asc.aop.TracingBeforeAdvice"/ > <bean id= "thetracingafteradvice" class= "Com.wow.asc.aop.TracingAfterAdvice"/> <bean id= "
 Thetracingthrowsadvice "class=" Com.wow.asc.aop.TracingThrowsAdvice "/> </beans>

Through the above configuration, we can see that we have Ibusinesslogic as the proxy interface, while its real target class is businessslogic. At the same time, the tracingbeforeadvice is used to intercept all incoming methods before the method is pre-processed, and the method uses Tracingafteradvice to intercept and to deal with the return of the methods.          For bar, Tracingthrowsadvice is used to intercept, and when the method returns to businesslogicexception the corresponding processing. After configuring the dependencies of the above classes and the methods that need to be intercepted, you can write a client program to invoke to see how it works. Client calling Code:

Package com.wow.asc.test;

Import Org.springframework.context.ApplicationContext;
Import Org.springframework.context.support.ClassPathXmlApplicationContext;
Import com.wow.asc.aop.BusinessLogicException;
Import Com.wow.asc.aop.IBusinessLogic;

public class Aoptest {public
    static void Main (string[] args) {
        ApplicationContext ac = new Classpathxmlapplicatio Ncontext ("Applicationcontext.xml");
        Ibusinesslogic IBL = (ibusinesslogic) ac.getbean ("Businesslogicbean");
        Ibl.foo ();
        try {
            ibl.bar ();
        } catch (Businesslogicexception e) {
            System.out.println ("Caught Businesslogicexception ");
        }
        Ibl.time ();
    }
}

By running the results to understand in detail, to see whether the actual above, the method before, after, and the exception can be intercepted and processed accordingly. The results are as follows:

1, execute before (by Com.wow.asc.aop.IBusinessLogic.foo)
2, Inside Businesslogic.foo ()
3, execute before (by Com.wow.asc.aop.IBusinessLogic.bar)
4, Inside Businesslogic.bar ()
5, Logging that a Com.wow.asc.aop.BusinessLogicExceptionException was thrown.
6, caught Businesslogicexception
7, execute before (by Com.wow.asc.aop.IBusinessLogic.time)
8, Inside Businesslogic.time ()
9, Com.wow.asc.aop.IBusinessLogic.timespend time:46
10, execute after Com.wow.asc.aop.IBusinessLogic.time)
In fact, through 1, 3, 7 lines can be very clear to understand that each method is tracingbeforeadvice intercepted before execution, and perform preprocessing. 5, 6 lines indicate that when the bar method is called, it will be intercepted by Tracingthrowsadvice, when an exception is thrown, the corresponding processing will be performed, 8, 9, 10 rows means that when the time method is called, the return will be intercepted by Tracingafteradvice, The return value is processed.

methodinterceptor Intercept Mode

To intercept in this way, you need to implement a class that inherits from Methodinterceptor and register that class with spring context, as follows:

Package COM.WOW.ASC.AOP;

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

public class Myinterceptor implements Methodinterceptor {
    @Override public
    Object Invoke (methodinvocation Invocation) {
        Object result = null;
        StringBuffer info = new StringBuffer ();
        Info.append ("Intercept the Method:");
        Info.append (Invocation.getmethod (). Getdeclaringclass ().
GetName ());
        Info.append (".");
        Info.append (Invocation.getmethod (). GetName ());
        System.out.println ("Start" + info.tostring ());
        try {
           result = Invocation.proceed ();
        } catch (Throwable e) {
            e.printstacktrace ();
        } finally {
            System.out.println ("End" + info.tostring ());
        }
        return result;
    }
}
The Assembly of the class, in fact, is very similar to the above, for example:

<bean id= "Testbean" class= "Org.springframework.aop.framework.ProxyFactoryBean" >
		<property name= " Proxyinterfaces ">
			<value>com.wow.asc.aop.IBusinessLogic</value>
		</property>
		<property name= "target" >
			<ref local= "businesslogic"/> 
		</property>
		<property Name = "Interceptornames" >
			<list>
				<value>myInterceptor</value>
			</list>
		</property>
</bean>
<bean id= "Myinterceptor" class= "Com.wow.asc.aop.MyInterceptor"/>
Then through the client to call, you can get the results of the operation, from the results of analysis can be seen in the method before and after the execution of the corresponding log added.

Start intercept the Method:com.wow.asc.aop.IBusinessLogic.foo
Inside businesslogic.foo ()
End intercept The Method:com.wow.asc.aop.IBusinessLogic.foo
start intercept the Method:com.wow.asc.aop.IBusinessLogic.time
Inside businesslogic.time ()
end intercept the Method:com.wow.asc.aop.IBusinessLogic.time
At this point, the implementation of AOP in two different ways is over, then the first configuration of the introduction of spring AOP approximate implementation principles and procedures.

Third, Spring AOP implementation process and principles
From the example above we can see that through Proxyfactorybean the target object target (in the example, Businesslogic) proxy object, we execute the proxy object of the Foo method, in fact, the method body does not have any specific logic, Instead, it executes the Invoke method of the Invocationhandler associated with it directly, which is the Invoke method (or Cglib2aopproxy intercept method) that executes jdkdynamicaopproxy in spring AOP. , if there is no interceptor setting in the Jdkdynamicaopproxy invoke method, then the corresponding method of the target object is called directly, whereas the interceptor will call the Reflectivemethodinvocation proceed method, In this method, all interceptors are traversed, if the current method matches the Poincut in the Interceptor (the Advisor object contains advice and Poincut objects, and the Interceptor object is adapted by the Advisor object), Then call the appropriate interceptor's Invoke method, and then call the corresponding advice method in the Invoke method, such as before,afterreturning, and so on, after all the interceptor calls are completed, the method of the proxy object is called.

Now there are two more questions about how the proxy object was created. Where did the interceptor come from?

The first question still has to be said from Proxyfactorybean that IOC is easy or the program calls the GetObject method of the class, Then Proxyfactorybean calls the Initializeadvisorchain method to read the relevant advisor from the configuration file, then calls its own Getsingletoninstance method, In this method will call Proxycreatorsupport (from the name can be seen that this is to create a Proxy object helper Class), and then will call Aopproxyfactory this proxy object factory Ctreateaopproxy method to generate proxy object, For example, Defaultaopproxyfactory's Ctreateaopproxy method, in this method will determine whether the target object is not an interface implementation class, if yes, create a aopproxy subclass Jdkdynamicaopproxy instance, Otherwise, a aopproxy subclass Cglib2aopproxy instance is created by Cglib2aopproxy's Createcglibproxy method, and then the proxy object can be returned through the Aopproxy method in the GetProxy implementation class.

The second problem is that the interceptor chain is obtained in the Jdkdynamicaopproxy invoke method, Obtained by Advisedsupport the Getinterceptorsanddynamicinterceptionadvice method of the object, Advisedsupport this helper class from the cache to obtain the interceptor chain, if not in the cache, Then use Defaultadvisorchainfactory's Getinterceptorsanddynamicinterceptionadvice method to obtain.

This is the understanding of spring AOP-related source code, if there is a wrong place to point out.








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.