Spring AOP instance

Source: Internet
Author: User

In the previous blog, I introduced you to the important concepts and tutorials of AOP. This section provides sample code.

I. xml

1. testaspect: partition class

package com.spring.aop;import org.aspectj.lang.JoinPoint;import org.aspectj.lang.ProceedingJoinPoint;public class TestAspect {public void doAfter(JoinPoint jp) {System.out.println("log Ending method: " + jp.getTarget().getClass().getName() + "." + jp.getSignature().getName());}public Object doAround(ProceedingJoinPoint pjp) throws Throwable {long time = System.currentTimeMillis();Object retVal = pjp.proceed();time = System.currentTimeMillis() - time;System.out.println("process time: " + time + " ms");return retVal;}public void doBefore(JoinPoint jp) {System.out.println("log Begining method: " + jp.getTarget().getClass().getName() + "." + jp.getSignature().getName());}public void doThrowing(JoinPoint jp, Throwable ex) {System.out.println("method " + jp.getTarget().getClass().getName() + "." + jp.getSignature().getName() + " throw exception");System.out.println(ex.getMessage());}}

2. aserviceimpl: target object

Package COM. spring. service; // use JDK dynamic proxy public class aserviceimpl implements aservice {public void resume () {system. out. println ("aserviceimpl. empty () ");} public void fooa (string _ MSG) {system. out. println ("aserviceimpl. fooa (MSG: "+ _ MSG + ")");}}

3. bserviceimpl: target object

Package COM. spring. service; // use cglibpublic class bserviceimpl {public void Barb (string _ MSG, int _ type) {system. out. println ("bserviceimpl. barb (MSG: "+ _ MSG +" type: "+ _ type +") "); If (_ type = 1) throw new illegalargumentexception ("test exception");} public void foob () {system. out. println ("bserviceimpl. foob ()");}}

4. applicationcontext: Spring configuration file

<? 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: AOP = "http://www.springframework.org/schema/aop" xmlns: context = "http://www.springframework.org/schema/context" xmlns: Tx = "http://www.springframework.org/schema/tx" xsi: schemalocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1. Xsdhttp: // www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd "> <AOP: config> <AOP: aspect id =" testaspect "ref =" aspectbean "> <! -- Configure COM. spring. all methods of all classes or interfaces under the service package --> <AOP: pointcut id = "businessService" expression = "execution (* COM. spring. service. *. *(..)) "/> <AOP: Before pointcut-ref =" businessService "method =" dobefore "/> <AOP: after pointcut-ref = "businessService" method = "doafter"/> <AOP: Around pointcut-ref = "businessService" method = "doaround"/> <AOP: after-throwing pointcut-ref = "businessService" method = "dothrowing" Throwing = "ex"/> </AOP: aspect> </AOP: config> <bean id = "aspectbean" class = "com. spring. AOP. testaspect "/> <bean id =" aservice "class =" com. spring. service. aserviceimpl "> </bean> <bean id =" bservice "class =" com. spring. service. bserviceimpl "> </bean> </beans>

 

Ii. Annotation

1. testannotationaspect

Package COM. spring. AOP; import Org. aspectj. lang. proceedingjoinpoint; import Org. aspectj. lang. annotation. after; import Org. aspectj. lang. annotation. afterreturning; import Org. aspectj. lang. annotation. afterthrowing; import Org. aspectj. lang. annotation. around; import Org. aspectj. lang. annotation. aspect; import Org. aspectj. lang. annotation. before; import Org. aspectj. lang. annotation. pointcut; @ aspectpublic class testannotationaspect {@ pointcut ("execution (* COM. spring. service. *. *(..)) ") Private void pointcutmethod () {}// declare the pre-notification @ before (" pointcutmethod () ") Public void dobefore () {system. out. println ("pre-notification");} // declare post-Notification @ afterreturning (pointcut = "pointcutmethod ()", returning = "result") Public void doafterreturning (string result) {system. out. println ("post notification"); system. out. println ("---" + Result + "---");} // declare the exception notification @ afterthrowing (pointcut = "pointcutmethod ()", throwing = "e ") public void doafterthrowing (exception e) {system. out. println ("exception notification"); system. out. println (E. getmessage ();} // declare the final notification @ After ("pointcutmethod ()") Public void doafter () {system. out. println ("final notification");} // declare the surround notification @ around ("pointcutmethod ()") Public object doaround (proceedingjoinpoint pjp) throws throwable {system. out. println ("access method --- surround notification"); object o = pjp. proceed (); system. out. println ("Exit method --- surround notification"); return o ;}}

2. applicationcontext: Spring configuration file

<?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:aop="http://www.springframework.org/schema/aop"xmlns:context="http://www.springframework.org/schema/context"xmlns:tx="http://www.springframework.org/schema/tx"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>    <bean class="org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator" />    <bean id="aspectBean" class="com.spring.aop.TestAnnotationAspect" />    <bean id="aService" class="com.spring.service.AServiceImpl"></bean>    <bean id="bService" class="com.spring.service.BServiceImpl"></bean></beans>

 

As for the entry point expression, you need to practice well before you can understand its meaning. Even though I understand it, it is very troublesome to write it, and it is not as simple as I think.

Finally, let us know:

Any notification (advice) method can define the first parameter as the org. aspectj. Lang. joinpoint type.JoinpointThe interface provides a series of useful methods, such as getargs () (Return method parameter), getthis () (return proxy object), gettarget () (return target), getsignature () (return information about the method being notified) and tostring ()
(Print out useful information about the method being notified.

Where getsignature () returnsSignatureObjects can be forcibly convertedMethodsignatureIt is very powerful and can obtain information about all methods including parameter names.

 

=============== Links ==============

Spring AOP detailed tutorial http://blog.csdn.net/wangpeng047/article/details/8556800

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.