Spring AOP Based on Annotation explanation and instance code, springaop

Source: Internet
Author: User

Spring AOP Based on Annotation explanation and instance code, springaop

Spring AOP Based on Annotation explanation and instance code

1. Enable spring support for @ AspectJ annotation:

<Beans xmlns: aop = "http://www.springframework.org/schema/aop"...> <! -- Enable support --> <aop: aspectj-autoproxy/> </beans>

You can also configure AnnotationAwareAspectJAutoProxyCreator Bean to enable Spring's support for @ AspectJ annotations.

<beans...>  <bean class="org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator" /></beans>

2. In order to start @ AspectJ support in the application, two AspectJ libraries, aspectjweaver. jar and aspectjrt. jar, need to be added to Yao. In addition, Spring AOP also depends on an aopllliance. jar package.

3. Define the slice Bean

@Aspectpublic class LogAspect {  //...}

4. Define enhancement processors, such as Before

@ Aspectpublic class LogAspect {@ Before ("execution (**. *. *(..)) ") public void authority () {System. out. println ("simulate permission check before executing the target method ");}}

@ AfterReturning annotation will be woven after the target method is completed normally. This annotation specifies the following two attributes:
1> pointcut/value: Specifies the cut-in expression corresponding to the start point.
2> returning: specify a parameter name for accessing the return value of the target method. If this parameter type is specified in the Advice method, the return value of the target method is limited to this type.

@ AfterThrowing annotation is used to handle exceptions that are not processed in the program. This annotation specifies the following link attributes:
1> pointcut/value: Specifies the cut-in expression corresponding to the start point.
2> throwing: This attribute value also specifies a parameter name to indicate the unprocessed exception thrown by the target method. If this parameter type is specified in the Advice method, the target method is limited to throw an exception of the specified type.

@ Around annotation is similar to the sum of Before and AfterReturning enhancement processing. It can determine when the target method is executed, because the first parameter of the Advice method modified by this annotation is of the ProceedingJoinPoint type, the ProceedingJoinPoint parameter has a proceed () method, which can be called to execute the target method. If this method is not displayed in the Advice method, the target method will not be executed:

@ Aspectpublic class LogAspect {@ Around ("execution (**. *. *(..)) ") public Object aroundAdvice (ProceedingJoinPoint jp) {System. out. println ("execute Around enhancement"); // obtain the original parameter Object [] args = jp. getArgs (); // obtain the returned Object result = jp. proceed (args); System. out. priontln ("completed aroundenhancement processing ");}}

5. to obtain information about the target method, you can define the first parameter as the JoinPoint type when defining the enhancement method. When this enhancement method is called, the JoinPoint parameter indicates the connection point for weaving enhancement. JoinPoint is similar to the ProceedingJoinPoint of the Around enhancement processing, except that the latter is specific to the use of the Around enhancement processing. JoinPoint contains the following common methods:

1> Object [] getArgs (): returns the parameter when the target method is executed. 2> Signature getSignature (): returns information about the method to be enhanced. 3> Object getTarget (): return the target Object of the woven increment processing. 4> Object getThis (): return the proxy Object generated by the AOP framework for the target Object.

Example Before: Enhance the processing to obtain information about the target method

@ Aspectpublic class LogAspect {@ Before ("execution (**. *. *(..)) ") public void beforeAdvice (JoinPoint jp) {// obtain the Object [] args = jp. getArgs (); System. out. println ("the parameter list of the target method is:" + Array. toString (args); // method name for obtaining the target method String methodName = jp. getSignature (). getName (); System. out. println ("method name of the target method:" + methodNamme); // obtain the target object LogAspect System of the woven enhancement. out. println ("the target object for Woven enhancement processing is:" + jp. getTarget ());}}

6. If two Advice instances in two different Aspect instances need to be implanted at the same JoinPoint connection point, Spring AOP will randomly weave the two enhancements. To specify their priority, you can use either of the following methods:

1> implement org. springframework. core. ordered interface, and implements its abstract method: int getOrder (); the smaller the return value of this method, the higher the priority. 2> directly use the @ Order annotation to modify the Aspect class, this annotation needs to specify an int value attribute value.

7. Define the Pointcut: contains two parts: a Pointcut expression and a method signature containing the name and any parameters:

@ Pointcut ("execution (**. *. *(..)) ") public void simplepointcut (){//...} // After Pointcut is defined, you can use the method name as the pointcut attribute value in other enhancement processes: @ Before (pointcut = "simplepointcut ()") // equivalent to pointcut = "execution (**. *. *(..)) "public void beforeAspect (){//...} // If the pointcut entry point is not the same class, you need to use the class to modify it, for example, @ Before (pointcut = "Simple. simplepointcut ()")...

8. Entry Point Indicator: This is the execution class specified in the previous enhancement process. It is used to specify the conditions to be met by the target method. Spring AOP supports the following entry point indicators:

1> execution: joinpoint used to match the execution method 2> within: used to limit the joinpoint that matches a specific type such as within (com. cheng. joinpoint. *) 3> this: specifies that the AOP proxy must be an instance of the specified type. All connection points matching the object, such as this (com. cheng. aop. aopService) 4> target: used to limit that the target exclusive instance must be of the specified type. 5> args: used to limit the parameter type of the connection point. The parameter type must be of the specified type, multiple parameter types are separated by commas (,). 6> bean: used to limit that only the connection points in the specified Bean instance are matched. The Bean id/name must be input.

9> finally, we need to use elements in the Spring configuration file to specify the automatic search partition class.

<Beans...> <! -- Specify the automatic search Bean component and automatic search partition class --> <context: component-scan base-package = "com. cheng "> <context: include-filter type =" annotation "expression =" org. aspectj. lang. annotation. aspect "/> </context: component-scan> </beans>

Thank you for reading this article. I hope it will help you. Thank you for your support for this site!

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.