Spring AOP annotation and xml implementation, Spring AOP annotation xml
AOP stands for the continuation of OOP and is short for Aspect Oriented Programming, which means Aspect-Oriented Programming. The pre-compilation method and runtime dynamic proxy can be used to dynamically and uniformly add functions to the program without modifying the source code. AOP is actually a continuation of the GoF design model. The design model tirelessly pursues decoupling between callers and callers. AOP can be said to be an implementation of this goal.
Some non-services we are doing now, such as logs, transactions, and security, will be written in the Business Code (that is, these non-business classes are cross-cutting in the business class ), but these codes are often repeated. Copying-pasted code will cause inconvenience to program maintenance, and AOP will split these business requirements from system requirements. This solution is also called a proxy mechanism.
First, let's take a look at the related concepts of AOP. The Spring Reference Manual defines the following important concepts of AOP. The code analysis is as follows:
- Aspect (Aspect ):The abstract definition of the official party is "modularization of a focus, which may cross multiple objects". In this example, the "aspect" is the specific behavior followed by TestAspect, for example, AServiceImpl. the call of lift () is one of the actions that concern TestAspect. "Aspect" is configured in ApplicationContext <aop: aspect>.
- Join point (Joinpoint): A row in the program execution process is, for example, a call to UserService. get or an exception thrown by UserService. delete.
- Advice): "Slice" indicates the action generated by a "connection point". For example, the log record action for methods of all classes under the com. spring. service package in TestAspect is an Advice. One slice can contain multiple "Advice", such as ServiceAspect.
- Pointcut): The assertion that matches the connection point. In AOP, it is notified to be associated with an entry point expression. For example, the connection points of all notifications in TestAspect are determined by the entry point expression execution (* com. spring. service.
- Target Object): The object to be notified by one or more slices. For example, AServcieImpl and BServiceImpl, of course, Spring AOP adopts proxy implementation during actual running, and actual AOP operates on the proxy object of TargetObject.
- AOP Proxy): There are two proxy methods in Spring AOP: JDK dynamic proxy and CGLIB proxy. By default, when TargetObject implements an interface, JDK dynamic proxy is used, for example, AServiceImpl. Otherwise, CGLIB proxy is used, for example, BServiceImpl. To use the CGLIB proxy, set the proxy-target-class attribute of <aop: config> to true.
Notification (Advice) type:
- Before advice ):A notification is executed before a connection point. However, this notification cannot be executed before a connection point. In ApplicationContext, use the <aop: before> element in <aop: aspect> for declaration. For example, the doBefore method in TestAspect.
- After advice ):The notification that is executed when a connection point exits (whether it is normal return or abnormal exit ). In ApplicationContext, use the <aop: after> element to declare in <aop: aspect>. For example, the returnAfter method in ServiceAspect, so when UserService. delete is called in Teser to throw an exception, the returnAfter method is still executed.
- After return notification (After return advice ):Notifications executed after a connection point is completed normally do not include exceptions thrown. In ApplicationContext, use the <after-returning> element in <aop: aspect> for declaration.
- Surround notification (Around advice ):Notifications that enclose a connection point, similar to the doFilter method of the Filter in the Servlet specification in the Web. You can customize the behavior before and after the method is called, or you can choose not to execute. In ApplicationContext, use the <aop: around> element in <aop: aspect> for declaration. For example, the round method in ServiceAspect.
- Notification After an exception is thrown (After throwing advice ):The notification that is executed when the method throws an exception and exits. In ApplicationContext, use the <aop: after-throwing> element in <aop: aspect> for declaration. For example, the returnThrow method in ServiceAspect.
Note:You can apply multiple notifications to a target object, that is, you can attach multiple slices to the same target object.
Spring AOP can be used in two ways. One is a convenient and powerful annotation method, and the other is a well-defined xml configuration method.
First, annotations are used to configure Spring AOP in two steps,
The first step is to declare activation of the automatic scanning component function in the xml file, and activate the automatic proxy function at the same time:
<? 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: context = "http://www.springframework.org/schema/context" xmlns: aop = "http://www.springframework.org/schema/aop" xsi: schemaLocation = "http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsdhttp://www.springframework.org/schema/beans http: // www .Springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd "> <! -- Activate the component scanning function. ysh. studio. spring. the components configured by annotation are automatically scanned under aop and its sub-packages --> <context: component-scan base-package = "cn. ysh. studio. spring. aop "/> <! -- Activate the automatic proxy function --> <aop: aspectj-autoproxy proxy-target-class = "true"/> <! -- User service object --> <bean id = "userService" class = "cn. ysh. studio. spring. aop. service. UserService"/> </beans>
The second step is to add an annotation for the Aspect partition class:
/*** System Service Component Aspect validation Bean * @ author Shenghany * @ date 2013-5-28 * // declare that this is a Component @ Component // declare that this is a validation Bean @ Aspectpublic class ServiceAspect {private final static Log log = LogFactory. getLog (ServiceAspect. class); // configure the entry point. This method has no method body. It is mainly used to facilitate other methods of the same type to use the entry point configured here @ Pointcut ("execution (* cn. ysh. studio. spring. aop. service .. *(..)) ") public void aspect () {}/** configure the pre-notification. Use the entry point registered on method aspect () * and accept the JoinPoint entry point object, this parameter does not exist. */@ Before ("Aspect ()") public void before (JoinPoint joinPoint) {if (log. isInfoEnabled () {log.info ("before" + joinPoint) ;}// configure the post-notification, using the entry point registered on method aspect () @ After ("aspect () ") public void after (JoinPoint joinPoint) {if (log. isInfoEnabled () {log.info ("after" + joinPoint) ;}// configure the surround notification, using the entry point registered on method aspect () @ Around ("aspect () ") public void around (JoinPoint joinPoint) {long start = System. currentTimeMillis (); try {(ProceedingJoi NPoint) joinPoint ). proceed (); long end = System. currentTimeMillis (); if (log. isInfoEnabled () {log.info ("around" + joinPoint + "\ tUse time:" + (end-start) + "MS! ") ;}} Catch (Throwable e) {long end = System. currentTimeMillis (); if (log. isInfoEnabled () {log.info ("around" + joinPoint + "\ tUse time:" + (end-start) + "MS with exception:" + e. getMessage () ;}}// configure the post-return notification, using the entry point registered on method aspect () @ AfterReturning ("aspect ()") public void afterReturn (JoinPoint joinPoint) {if (log. isInfoEnabled () {log.info ("afterReturn" + joinPoint) ;}// notification after the configuration throws an exception, used in method aspect () the entry point registered on @ AfterThrowing (pointcut = "aspect ()", throwing = "ex") public void afterThrow (JoinPoint joinPoint, Exception ex) {if (log. isInfoEnabled () {log.info ("afterThrow" + joinPoint + "\ t" + ex. getMessage ());}}}
Test code:
/*** Spring AOP test * @ author Shenghany * @ date 2013-5-28 */public class Tester {private final static Log log Log = LogFactory. getLog (Tester. class); public static void main (String [] args) {// start Spring container ApplicationContext context = new ClassPathXmlApplicationContext ("applicationContext. xml "); // get the service component UserService service = (UserService) context. getBean ("userService"); // call the three methods of the UserService object in the normal way: User user = service. get (1L); service. save (user); try {service. delete (1L);} catch (Exception e) {if (log. isWarnEnabled () {log. warn ("Delete user:" + e. getMessage ());}}}}
The console output is as follows:
INFO [spring. aop. aspect. serviceAspect: 40] before execution (User cn. ysh. studio. spring. aop. service. userService. get (long) INFO [spring. aop. service. userService: 19] getUser method... INFO [spring. aop. aspect. serviceAspect: 60] around execution (User cn. ysh. studio. spring. aop. service. userService. get (long) Use time: 42 MS! INFO [spring. aop. aspect. serviceAspect: 48] after execution (User cn. ysh. studio. spring. aop. service. userService. get (long) INFO [spring. aop. aspect. serviceAspect: 74] afterReturn execution (User cn. ysh. studio. spring. aop. service. userService. get (long) INFO [spring. aop. aspect. serviceAspect: 40] before execution (void cn. ysh. studio. spring. aop. service. userService. save (User) INFO [spring. aop. service. userServic E: 26] saveUser method... INFO [spring. aop. aspect. serviceAspect: 60] around execution (void cn. ysh. studio. spring. aop. service. userService. save (User) Use time: 2 MS! INFO [spring. aop. aspect. serviceAspect: 48] after execution (void cn. ysh. studio. spring. aop. service. userService. save (User) INFO [spring. aop. aspect. serviceAspect: 74] afterReturn execution (void cn. ysh. studio. spring. aop. service. userService. save (User) INFO [spring. aop. aspect. serviceAspect: 40] before execution (boolean cn. ysh. studio. spring. aop. service. userService. delete (long) INFO [spring. aop. service. userService: 32] delete method... INFO [spring. aop. aspect. serviceAspect: 65] around execution (boolean cn. ysh. studio. spring. aop. service. userService. delete (long) Use time: 5 MS with exception: spring aop ThrowAdvice demo INFO [spring. aop. aspect. serviceAspect: 48] after execution (boolean cn. ysh. studio. spring. aop. service. userService. delete (long) INFO [spring. aop. aspect. serviceAspect: 74] afterReturn execution (boolean cn. ysh. studio. spring. aop. service. userService. delete (long) WARN [studio. spring. aop. tester: 32] Delete user: Null return value from advice does not match primitive return type for: public boolean cn. ysh. studio. spring. aop. service. userService. delete (long) throws java. lang. exception
The xml configuration method is also simple:
<? 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: context = "http://www.springframework.org/schema/context" xmlns: aop = "http://www.springframework.org/schema/aop" xsi: schemaLocation = "http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsdhttp://www.springframework.org/schema/beans http: // www .Springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd "> <! -- System Service component validation Bean --> <bean id = "serviceAspect" class = "cn. ysh. studio. spring. aop. aspect. ServiceAspect"/> <! -- AOP configuration --> <aop: config> <! -- Declare a plane and inject the Bean, which is equivalent to @ Aspect --> <aop: aspect id = "simpleAspect" ref = "serviceAspect"> <! -- Configure an entry point, which is equivalent to @ Pointcut --> <aop: pointcut expression = "execution (* cn. ysh. studio. spring. aop. service .. *(..)) "id =" simplePointcut "/> <! -- Configure the notification, which is equivalent to @ Before, @ After, @ AfterReturn, @ Around, @ AfterThrowing --> <aop: before pointcut-ref = "simplePointcut" method = "before"/> <aop: after pointcut-ref = "simplePointcut" method = "after"/> <aop: after-returning pointcut-ref = "simplePointcut" method = "afterReturn"/> <aop: after-throwing pointcut-ref = "simplePointcut" method = "afterThrow" throwing = "ex"/> </aop: aspect> </aop: config> </beans>
Generally, the use of "execution" in the expression can meet most of the requirements. The expression format is as follows:
1) execution (**(..))
Indicates matching all methods
2) execution (public * com. savage. service. UserService .*(..))
Matches all public methods in com. savage. server. UserService.
3) execution (* com. savage. server ..*.*(..))
Match all methods in the com. savage. server package and its sub-Package
In addition to the execution representation, there are Pointcut representations such as within, this, target, and args. A Pointcut definition consists of a Pointcut expression and a Pointcut signature.
execution(modifiers-pattern? ret-type-pattern declaring-type-pattern? name-pattern(param-pattern) throws-pattern?)
- Modifiers-pattern: Operation permission of the Method
- : Return Value
- : Method package
- : Method Name
- : Parameter Name
- : Exception
Ret-type-pattern Declaring-type-pattern Name-pattern Parm-pattern Throws-pattern
Among them, except ret-type-pattern and name-pattern, others are optional. In the preceding example, execution (* com. spring. service. *. *(..)) com. spring. under the service package, the return value is of any type; the method name is arbitrary; all methods with no restrictions on parameters.
When defining Pointcut, you can also use &, | ,! Operations, such
Source: http://ntzrj513.blog.163.com/blog/static/27945612201362232315/
Source: http://www.eclipse.org/aspectj/doc/released/runtime-api/org/aspectj/lang/Signature.html