Spring Study Notes (4) Advices

Source: Internet
Author: User

Spring AOP Advices

Advices implements the real logic of Aspect. Specifically, in java, It is a class or more fine-grained design into a method (one class centrally manages multiple Advices ). Spring provides several different Advices, such as Before Advices, After Advices, Around Advices, and Throw Advice.

1. Before Advices

Before Advices will be called Before the method of the target object is executed. You can call the org. springframework. aop. MethodBeforeAdvice interface to implement the Before Advice logic. The interface is defined as follows:

Public interface MethodBefore extends BeforeAdvice {

Void before (Method method, Object [] args, Object target) throws Throwable;

}

BeforeAdvice inherits from the Advice interface, and both are label interfaces. There is no way.

The before () Method is executed before the Method specified by the Target object is executed. The executed Method Instance, parameter object array, and Target object can be obtained.

Example:

Public interface IHello {

Public void hello (String name );

}

HelloSpeaker class:

Public class HelloSpeaker implements IHello {

Public void hello (String name ){

System. out. println ("Hello" + name );

}

}

HelloSpeaker is equivalent to a component. If there is no source code, add some log functions before its method to implement the MethodBeforeAdvice interface, for example:

.....

Public class LogBeforeAdvice implements MethodBeforeAdvice {

Private Logger logger = Logger. getLogger (this. getClass (). getName ());

Public void before (Method method, Object [] args, Object target) throws Throwable {

Logger. log ("method starts" + method );

}

}

Ii. After Advices

After Advices is called After the target method is executed. You can implement the org. springframework. aop. AfterReturningAdvice interface to implement the After Advice logic. The AfterReturningAdvice interface is defined as follows:

Public interface AfterReturningAdvice extends Advice {

Void afterReturning (Object returnValue, Method m, Object [] args, Object target)

Throws Throwable;

}

Implementation class:

Public class LogAfterAdvice implements AfterReturningAdvice {

Private Logger logger = Logger. getLogger (this. getClass (). getName ());

Public void afterReturning (............){

Logger. log ("method ends" + method );

}

}

Add the following example to the configuration file:

<Bean id = "logBeforeAdvice" class = "..."/>

<Bean id = "logAfterAdvice" class = "..."/>

<Bean id = "hellospeaker" class = "..."/>

<Bean id = "helloproxy" class = "org. springframework. AOP. Framework. proxyfactorybean">

<Property name = "proxyinterfaces" value = "... ihello"/>

<Property name = "target" value = "... hellospeaker "/.

<Property name = "interceptornames">

<List>

<Value> logbeforeadvice </value>

<Value> logafteradvice </value>

</List>

</Bean>

In fact, you can design a class to implement these two interfaces at the same time. Here, we only demonstrate how to separate advice.

3. Around advices

If you add the advices service before and after the method execution, you can directly implement the org. aopalliance. Intercept. methodinterceptor interface. Definition:

Public interface methodinterceptor {

Public Object invoke (MethodInvocation methodInvocation) throws Throwable;

}

This interface is specified by the AOP Alliance and can be compatible with the AOP framework complying with the AOP Alliance specification.

The difference is that in the invoke () method of MethodInterceptor, you have to decide whether to execute the proceed () method of methodInvocation to execute the target object. Proceed () returns the execution result, so you can have the opportunity to modify this object and return other values before invoke () ends. For example:

Public class LogInterceptor implements MethodInterceptor {

Private Logger logger = Logger. getLogger (this. getClass (). getName ());

Public Object invoke (MethodInvocation methodInvocation) thorws Throwable {

Logger. log ("method start" + methodInvocation. getMethod ());

Object result = null;

Try {

Result = methodInvocation. proceed ();

}

Finally {

Logger. log ("method ends" + methodInvoacation. getMehod ());

}

Return result;

}

}

The configuration file definition is the same as before. Just change the name.

Iv. Throw Advices

To notify certain service objects of some things when an exception occurs, you can use Throws Advice to implement org. springframework. aop. throwsAdvice interface. However, this interface does not define any methods. You can define the afterThrowing method as follows:

AfterThrowing ([Method], [args], [target], subclassOfThrowable );

When an exception occurs, Throw Advice only executes the corresponding method and cannot process the exception in Throws Advice. After Throw Advice is executed, the original exception is still transmitted to the application, exception Handling is still the responsibility of the application itself. If you want to abort the processing process of the application during Throw Advice processing, other exceptions will be thrown. For example:

Public interface IHello {

Public void hello (String name) throws Throwable;

}

Then define the class and simulate exceptions in the hello () method:

Public class HelloSpeaker implements IHello {

Public void hello (String name) throws Throwable {

System. out. println ("Hello" + name );

Throw new Exception ("Exception ...");

}

}

If you want to intervene in Throw Advice to provide some services when an application throws an exception, for example, recording some exception information, you can implement the ThrowAdvice interface.

Public class SomeThrowAdvice implements ThrowsAdvice {

Private Logger logger = Logger. getLogger (this. getClass (). getName ());

Public void afterThrowing (Method method, Object [] args, Object target, Throwable subclass ){

Logger. log (subclass + "Exception wa thrown in" + method );

}

}

Customer program:

.......

ApplicationContext ac = new ClassPathXmlApplicationContext ("conf. xml ");

IHello helloProxy = ac. getBean ("helloProxy ");

Try {

HelloProxy. hello ("Justin ");

}

Catch (Throwable throwable ){

System. err. println (throwable );

}

As shown above, Throw does not intervene in exception handling, but adds the logging function. Exception Handling is handled in the application itself.

 

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.