Spring Interceptor

xiaoxiao2021-03-18  198

Spring Interceptor

1 Spring notification type

Let us now look at how Spring AOP handles notifications.

1.1

Notice of life cycle

Spring notifications can span multiple notified objects, or each notified object has its own notification. This corresponds to the Per-Class or Per-Instance Notification.

The PER-CLASS notification is the most widely used. It is suitable for general notifications such as transaction Adisor. They do not rely on the status of the object being proxy, nor does it add new states. They only act on methods and methods parameters.

The Per-instance notifies the import to support mixing (Mixin). In this case, the notification is added to the object being proxy.

You can mix the sharing and PER-Instance notifications in the same AOP agent.

1.2

Notification type in Spring

Spring provides several ready-made notification types and extensible to provide any notification type. Let us look at the basic concepts and standard notification types.

1.2

.1. Interception Around Advice

The most basic notification type in Spring is Interception Around Advice.

Spring uses method interceptor's Around Notification is compatible with the AOP alliance interface. Classes that implement around notifications require the interface methodInterceptor:

Public interface methodinterceptor extends interceptor {

Object Invoke (MethodInvocation Invocation) throws throwable;

}

The INVOKE () method's methodinvocation parameter exposed the method, target connection point, AOP proxy, and parameter passed to the called method. The Invoke () method should return the result of the call: the return value of the connection point.

A simple MethodInterceptor implementation looks as follows:

Public class debuginterceptor imports methodinterceptor {

Public Object Invoke (MethodInvocation Invocation) throws throwable {

System.out.println ("Before: Invocation = [" Invocation "]");

Object rval = invocation.proceed ();

System.out.println ("Invocation Returned");

Return RVAl;

}

}

Note the call of the process () method for MethodInvocation. This call is applied to each interceptor chain in the target connection point. Most interceptors call this method and return its return value. However, like a MethodInterceptor, as any around notification, you can return different values ​​or throw an exception without calling the Proceed method. However, there is no good reason you want to do this.

MethodInterceptor provides interaction capabilities with other AOP alliances. The other notification types to be discussed below implements the concept of AOP public, but in a Spring-specific way. Although there are many advantages in using a specific notification type, if you may need to use in other AOP frameworks, please insist on using the MethodInterceptor Around Notification Type. Note that the current entry point cannot interact with other frameworks, and the AOP alliance currently does not define an entry point interface.

1.2

.2. Before notification

The Before notification is a simple notification type. This notification does not require a MethodInvocation object because it is only called before entering a method.

The main advantage of the Before notification is that it does not need to call the proceed () method, so there is no possibility that the interceptor chain is not inadvertently forgetting. The MethodbeforeAdvice interface is as follows. (Spring's API design allows member variables of Before notifications, although general objects can apply member variables to intercept, Spring may never implement it).

Public interface methodberedbeforeadvice extends beforeadvice {

Void Before (Method M, Object [] Args, Object Target.

}

Note that the return type is Void. The Before notification can insert a custom behavior before the connection point is executed, but the return value cannot be changed. If a Before notification throws an exception, this will interrupt the further execution of the interceptor chain. This exception will be spread upwards along the interceptor chain. If this exception is unchecked, or in the signature of the method being called, it will be passed directly to the customer code; otherwise, it will be packaged by the AOP agent to a unchecked exception.

Below is an example of a Before notification in Spring, this example counts all normal returns:

Public Class CountingBeforeadvice Implements MethodbeforeAdvice {

PRIVATE INT COUNT;

Public void before (Method M, Object [] args, object target) throws throwable {

COUNT;

}

Public int getCount () {

Return count;

}

}

The Before notification can be used for any type of entry point.

1.2

.3. Throws notice

If the connection point throws an exception, the throws notification is called after the connection point returns. Spring provides a strong type of THROWS notification. Note that this means that the org.springframework.aop.ThrowSAdvice interface does not contain any way: it is a tag interface that identifies a given object to implement one or more strong type Throws notification methods. These methods are as follows:

AfTHROWING ([Method], [Args], [Target], SubclassOfthrowable)

Only the last parameter is required. This is from one parameter to four parameters, depending on whether the notification is interested in the parameters of the method and method. Below is an example of the THROWS notification.

This notification will be called if the RemoteException exception (including subcategory) is thrown.

Public Class RemoteThrowSadvice Implements throwsadvice {

Public void atThrowing (RemoteException EX) throws throwable {

// Do Something with Remote Exception

}

}

If you throw a servleTException exception, the following notice will be called. And the above notice is different, it declares four parameters, so it can access the modified methods, the parameters and target objects:

Public static class servletthrowsadvicewitharguments imports throwsadvice {

Public void afterThrowing (Method M, Object [] args, object target, servletexception ex) {

// do Something Will All Arguments

}

}

The last example demonstrates how to use two methods in a class to simultaneously process RemoteException and servleTexception exception. Any number of THROWS methods can be combined in a class. Public Static Class CombinedthrowSadvice Implements throwsadvice {

Public void atThrowing (RemoteException EX) throws throwable {

// Do Something with Remote Exception

}

Public void afterThrowing (Method M, Object [] args, object target, servletexception ex) {

// do Something Will All Arguments

}

}

The ThROWS notification can be used for any type of entry point.

1.2

.4.4.After return notification

TheAfter Returning notification in Spring must implement org.springframework.aop.AfterReturningAdvice interface, as shown below:

Public interface afterReturningAdvice Extends advice {

Void afterReturning (Object ReturnValue, Method M, Object [] Args, Object Target

Throws throwable;

}

After ReturNing Notifications You can access the return value (cannot be changed), the parameters, methods of the method, method of the method, and the target object.

The following After Returning Notification Statistics All successful methods are called:

Public class countingafterreturningadvice implements afterReturnGAdvice {

PRIVATE INT COUNT;

Public void afterreturning (Object ReturnValue, Method M, Object [] Args, Object Target) throws throwable {

COUNT;

}

Public int getCount () {

Return count;

}

}

This method does not change the execution path. If it throws an exception, this exception is not the return value will be thrown upward along the interceptor chain.

After returbuning notifications can be used for any type of entry point.

1.2

.5. Introduction Notice

Spring Waizards Introduction as a special type of interception notification.

Introduction needs to implement IntroductionAdvisor, and IntroductionInterceptor interface:

Public interface IntroductionInterceptor Extends methodInterceptor {

Boolean ImplementsInterface (Class Intf);

}

Invoke () method inheriting from the AOP League MethodInterceptor interface must be imported:

The Introduction Notification cannot be used for any entry point because it can only act on a class level, not a method. You can use InterceptionIntroductionAdvisor to implement import notifications, which have the following methods:

Public Interface InterceptionintroductionAdvisor Extends InterceptionAdvisor {ClassFilter getClassFilter ();

IntroductionInterceptor getIntroductionInterceptor ();

GetInterfaces ();

}

There is no MethodMatcher here, so there is no correction point associated with the import notification. Only class filter is logical.

GetInterfaces () method Returns an Advisor imported interface.

Let's take a look at a simple example from the Spring test suite. We assume that you want to import the following interfaces to one or more objects:

Public interface lockable {

Void Lock ();

Void UNLOCK ();

Boolean locked ();

}

This example demonstrates a Mixin. We want to convert the notified object type to Lockable, regardless of their type, and call the Lock and UNLOCK methods. If we call the Lock () method, we hope that all setter methods will throw the LockedException exception. This way we can add an object that makes it untroven, and they don't need to know this: This is a very good AOP example.

First, we need an IntroductionInterceptor that makes a lot of transformation. Here, we inherit the org.springframework.aop.support.delegatingInTroductionInterceptor Practical class. We can directly implement an IntroductionInterceptor interface, but most of the situation is the most appropriate.

DelegatingIntroductionInterceptor is designed to be imported into an interface that is truly implemented to import interfaces, hiding interceptors of these work. The entrustment can be set to any object using the constructor parameter; the default delegate is ourselves (when the configuration method without parameters is used). In this way, the delegation is a subclass of DelegatingIntroductionInterceptor LockMixin. Given a delegatingIntroductionInterceptor instance for a delegate (default is your own) Find all interfaces implemented by this delegate (not IntroductionInterceptor) and supports any of them. Subclasses such as LockMixin may also call the SuppressInterflace (Class INTF) method hide the interface that should not be exposed. However, regardless of the how to support, IntroductionAdvisor will control which interface will be actually exposed. An imported interface will hide all the implementations of the same interface of the target.

This way, LockMixin inherits DelegatingIntroductionInterceptor and implements Lockable itself. The parent class automatically selects the imported Lockable, so we don't need to specify it. In this way we can import any number of interfaces.

Note the use of the Locked instance variable. This effectively adds additional status to the target object.

Public Class Lockmixin Extends DelegatingIntroductionInterceptor

IMPLEMENTS LOCKABLE {

PRIVATE BOOLEAN LOCKED;

Public void lock () {

THISLOCKED = TRUE;

}

Public void UNLOCK () {

THIS.LOCKED = FALSE;

}

Public Boolean Locked () {Return this.locked;

}

Public Object Invoke (MethodInvocation Invocation) throws throwable {

IF (Locked () && infocation.getMethod (). getname (). Indexof ("set") == 0)

Throw new LockedException ();

Return super.invoke (invocation);

}

}

Never need to rewrite the invoke () method: Implement DelegatingIntroductionInterceptor is enough. If it is an imported method, the DelegatingIntroductionInterceptor implementation will call the delegate method, otherwise continue along the connection point. In the present situation, we need to add a check: You cannot call the setter method in the locked state.

The imported Advisor required is very simple. Only saved a separate LockMixin instance and specifies the imported interface, here is Lockable. A slightly complex example may require a reference to an imported interceptor (which can define prototype): In this case, LockMixin has no relevant configuration, so we simply use New to create it.

Public class lockmixinadvisor extends defaultintroductionAdvisor {

Public lockmixinadvisor () {

Super (New LockMixin (), Lockable.class;

}

}

We can use this Advisor very simply: it does not need any configuration. (However, it is necessary: ​​it is impossible to use IntroductionInterceptor in the case of IntroductionAdvisor.) And import, usually the Advisor must be for each instance and is status. We will have different LockMixinadvisor each notified object, there will be different LockMixin. The Advisor constitutes a part of the state of the notified object.

Like other Advisor, we can use the Advied.Addadvisor () method to programmatically use this Advisor, or configure this in XML (recommend this way). All proxy creation will be discussed below, including Auto Agent Creation, select the agent to create to correctly process import and state mixing.

References: 1. Http://www.javaresearch.org/Article/showArticle.jsp?column=23&thread=41315 2. Http://tech.ccidnet.com/Art/1112/20051114/371959_5.html 3. Http://www.7dspace.com/doc/21/0603/20063305365394884.htm 4. Http://barton131420.cnblogs.com/articles/280664.html 5. Http://www.opentown.info/bbs/viewtopic.php?t=7

转载请注明原文地址:https://www.9cbs.com/read-129820.html

New Post(0)