Basic use of Spring AOP

Source: Internet
Author: User

Aop

First, what is AOP

AOP is the abbreviation of face-oriented programming, the program runs the process of decomposition into various facets, you can not modify the source code to the program method dynamically add functionality, its underlying implementation is the use of dynamic proxy mode;

Second, why use AOP

Separating the various concerns in the system, separating the core concerns from the crosscutting concerns (for example, the main business program and some program separation of check, log, security Class) to realize the decoupling of business logic and plane logic;

Third, the realization effect

You can add other operations before and after the method, such as: after each database query operation, to be added a log, and add the operation of the log we do not have to write in the database query this method, but by the AOP framework to do; After using dynamic proxy, every time we execute this database query method, Will be intercepted by the AOP framework to enhance the method, add some other operations before and after the method, we call the method (such as the database Query method), called the connection point (Joinpoint);

Iv. How to configure using annotations (implemented using the AspectJ class library)

0. jar Package

Aspectiweaver.jar Aopaliance-.jar Asperctjrt.jar

    1. Basic Configuration

(0) IOC container annotations are configured as usual

(1) First, to declare a class as a tangent, you need to put the class in the IOC container (configure its bean), and then declare it as a tangent, that is, add @aspect and @component to the class above the two annotations

(2) Add an AOP namespace to the XML configuration file and write to the beans tag:

<aop:aspectj-autoproxy></aop:aspectj-autoproxy>

Represents the automatic generation of proxy objects for matching methods;

    1. Pre-notification (action done before the target method is executed)

(1) Add a method to the slice class and add an annotation before the method:

@Before ("Execution (matching target method)")

The values in parentheses are called pointcut expressions and can be used with fuzzy matching (e.g. *./)

The expression format is: The full qualified name of the Access return value method (parameter type)

(2) The pre-notification method can have a type of joinpoint parameter

This parameter allows you to obtain various parameters of the target method, such as the method name, list of parameter values, class ...

    1. Post notification (actions done after the target method has been executed)

(1) The use of @after annotations, and the pre-notification function corresponds;

(2) Even if the target method has been abnormal, the post-notification is still executed;

(3) Neither the front-end notification nor the post-notification can access the return result of the target method;

    1. Back to Notifications

(1) methods to be executed after the normal end of the method;

(2) Use before the method:

@AfterReturning (value= "Execution (matching target method)", returning= "variable name")

(3) Add the object variable name to the parameter of the method (the variable name corresponds to the variable name in the annotation), and the return value of the target method can be accessed within the return notification method;

    1. Exception notification

(1) Use when the target method has an exception;

(2) by adding before the method:

@AfterThrowing (value= "Execution (matching target method)", throwing= "variable name")

(3) Add the exception type variable name (which corresponds to the variable name in the annotation) in the parameter of the method to access the exception thrown by the target method within the exception notification method

    1. Order of execution of the four notifications above

Back-to-front notification with exception--

    1. Surround Notifications

(1) Surround notification is equivalent to the entire process of dynamic agent, including the above four notifications

(2) Add @around ("Execution (matching target method)" before method)

(3) Add the Proceedingjoinpoint type parameter to the parameter of the method, use the. Proceed () of the type parameter, and the method can control the execution of the target method, and the return value of the method is the return value of the target method;

(4) Similarly, the Proceedingjoinpoint type parameter can also get the method name of the target method and the value of the parameter;

(5) The surround notification method must have a return value;

    1. Cut-Plane priority

When there is more than one slice class, use @order (integer value), the note is written on the slice class, the lower the value, the higher the priority;

    1. reusing pointcut expressions

(0) We write the pointcut expression executtion (...) in the annotations of each notification method, the values inside are likely to be the same, so wrap them up for reuse;

(1) Write an empty method (that is, the method does not write any code);

(2) Add @pointcut ("Execution (matching target method)" before method);

(3) Then, in the annotations of other notices, the "Execution (matching target method)" can be replaced with the method name;

(4) Cross-class, cross-package reference needs to add the corresponding class, package prefix;

V. How to configure using XML files (implemented using the AspectJ class library)
    1. (1) The Slice class first has to be a bean, so in the XML configuration file, the slice class must first be configured as a bean;

(2) The circular method code in the slice class and the slice class is consistent with the code of the annotation configuration;

    1. AOP Basic Configuration

(1) write the <aop:config></aop:config> tag first, then all the AOP configuration is written in the tag;

(2) Configure Pointcut Expressions:

<aop:pointcut expression= "Execution (matching method name)" id= "This expression id" >

The expression specifies the target method, which, when executed, is intercepted by the notification that the expression was invoked;

(3) Configure facets:

<aop:aspect ref= "Slice class bean" order= "priority integer value" ></aop:aspect>

Then, the notice belonging to the plane is written in the label;

(4) Configuration notification:

<aop:before method= "Method name in Slice class" pointcut-ref= "Pointcut expression ID" >

The return, post, exception, surround notification configuration is similar; notice that the variable name of the exception notification and the return notification is consistent with the variable name of the method parameter;

(5) The <aop:config> tag can have multiple facets configuration labels, and there can be more than one notice in the slice label;

(6) To use the target bean, the be an,aop to get the target object is automatically generated agent, automatic weaving;

    1. You need to write the notification to a class and inherit the corresponding interface:
    2. Configuration
Vi. How to configure XML files using the Spring Framework's own AOP implementation
Post notification: Afterreturningadvice exception notification: Throwsadvice

(1) Configure the target object, each notification method (called a slice) as a bean

(2) The proxy object is also configured as a bean, the ID is arbitrary,

Class= "Org.springframework.aop.framework.ProxyFactoryBean"

There are three parameters respectively:

Interceptornames, value is the list of facets (<list><value> notice/advisor Beanid</value> ...)

Target, value <ref= "target object Beanid" >

Interfaces, is the target object implementation of the interface list (<list><value> interface path </value>.)

(3) to get the Beanid of the proxy object when using the target object;

    1. Using the name matching Method pointcut Advisor (advisor)

(0) Advisory Packaging Notice, let the notice more finely woven into

(1) When the consultant is not used, the notification action is implemented by default for all methods of the target object, and the consultant can be used to specify which methods to intercept more finely;

The consultant will be configured to Bean,id as a free

Class= "Org.springframework.aop.support.NameMatchMethodPointcutAdvisor"

(2) The consultant has two or three parameters: advice, the value is the reference type, the Beanid that refers to the notification (that is, you want a notification to accurately function a certain/some method); Mappedname/mappednames, the first is the value type, specifies the target method name, The second is the array type, specifying multiple method names (the second value can also be written in value, each method name separated by a comma);

(3) The value of Mappednames can be matched with a * number, such as do*, specifying all methods starting with Do

(4) A consultant is also a facet, so when using a consultant, place it as a notification into the Interceptornames parameter in the proxy object bean

    1. Using regular expression matching method pointcut Advisor (advisor)

(0) Similar to the "Name matching method entry point";

(1) class to be replaced by org.springframework.aop.support.RegexpMethodPointcutAdvisor

(2) The consultant also needs three parameters: advice, using the same method as above;

Pattern/patterns: Its value is a regular expression (in fact, multiple expressions can be written in the pattern, separated by |);

(3) Common regular expression operators have. Represents any single character,

* indicates that the previous character appears 0 or more times + indicates that the previous character appears 1 or more times;

(4) The regular expression matches the fully qualified name of the method (package. Class. Method name);

(5) Example:. *do.* the fully qualified name represents the method that contains do;

    1. Default Advisor Auto Agent

(0) If you do not use an automatic agent, if there are multiple target objects, you need to manually configure multiple proxy objects, resulting in code redundancy and time-consuming;

(1) The Default Advisor Auto Agent uses the Bean's post processor (beanpostprocessor), which automatically generates proxy objects for all target objects in the configuration file after the bean is initialized and automatically binds the Consultants , and need to use the target object, only need to get the target object Beanid on it;

(2) configuration: The target object, notification, advisor Bean configuration is still the same, only need to add more than the following beans:

<bean class= "Org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" >

(3) The disadvantage: The plane of the automatic agent can only be advisor, can not specify the target object;

    1. Bean Name Auto Proxy generator

(0) You can specify the target object to which you want the proxy, and you need to specify the slice manually (which can be a notification or a consultant);

(1) Configuration: The target object, notification, advisor Bean configuration is still the same, only need to add more than the following beans:

<bean class= "Org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator" >

(2) The bean needs to use two parameters: the Beannames,value value is the Beanid of the target object, separated by commas when there are multiple Beanid, and the Interceptornames,value value is the tangent plane Beanid, When there are multiple beanid, use commas to separate;

    1. Cglib Agent

(0) The above mentioned agent is the JDK dynamic agent, in the proxy object configuration needs to specify the target object interface;

(1) And when the target object does not have an interface, spring AOP automatically uses the Cglib proxy (and, of course, the interface is not specified in the proxy object configuration);

(2) When the target object has an interface, you can also specify the use of the Cglib proxy: In the proxy object configuration, plus the Proxytargetclass parameter, the parameter value of True|false, true, force the use of Cglib proxy;

You can also use the optimize parameter, value is also True|false, when True, the interface is specified using the JDK proxy, no interface uses the Cglib proxy;

(3) JDK agent and cglib Agent difference: JDK creates proxy object fast, but execution is slow; cglib is the opposite;

(4) Note: The JDK dynamic Agent uses the reflection mechanism to generate an anonymous class that implements the proxy interface, calling Invokehandler to process before invoking the specific method.

The Cglib dynamic agent is the use of ASM Open Source package, the class file of proxy object classes loaded in, by modifying its bytecode generation subclass to deal with.

PS. Please also refer to the jar packages that need to be used during the development process.

Basic use of Spring AOP

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.