1. Waiter Target Class
1 PackageCom.smart.aop.advice.pointcut;2 3 Public classWaiter {4 5 Public voidGreetto (String name) {6System.out.println ("Waiter greet to" + Name + "...");7 }8 9 Public voidServerto (String name) {TenSYSTEM.OUT.PRINTLN ("Waiter server to" + name + "..."); One } A}
2. Defining facets using ASPECTJ annotations
1 PackageCOM.SMART.AOP.ADVICE.ASPECTJ;2 3 ImportOrg.aspectj.lang.annotation.Aspect;4 ImportOrg.aspectj.lang.annotation.Before;5 6 @Aspect7 Public classPregreetingaspect {8 9@Before ("Execution (* Greetto (..))")//define connection point (connection point azimuth information--front enhancement, pointcut--Greetto method for all target classes--can take arbitrary arguments and return values)Ten Public voidbeforegreeting () { OneSystem.out.println ("How is you!"); Method body for enhanced logic A } -}
3. Through the programming way to weave into the plane, for the waiter to weave into the XXX plane agent
1 PackageCOM.SMART.AOP.ADVICE.ASPECTJ;2 3 Importorg.springframework.aop.aspectj.annotation.AspectJProxyFactory;4 Importorg.testng.annotations.Test;5 ImportCom.smart.aop.advice.pointcut.Waiter;6 7 8 Public classAspectjproxytest {9 Ten @Test One Public voidbeforetest () { A -Waiter Waiter =Newwaiter (); -Aspectjproxyfactory pfactory =Newaspectjproxyfactory (); the -Pfactory.settarget (waiter);//set the target instance -Pfactory.addaspect (Pregreetingaspect.class);//Add Slice class - +Waiter Proxywaiter = Pfactory.getproxy ();//to generate a proxy object for the weaving agent - + /** A * Execution (* Greetto (..)) by tangent information in the slice class at * The Greetto method of proxy object Proxywaiter is woven into the enhanced logic defined by the slice class - */ -Proxywaiter.greetto ("Jack"); -Proxywaiter.serverto ("Jack"); - } -}
Output Result:
How is you!
Waiter greet to Jack ...
Waiter Server to Jack ...
4. Weaving slices through spring configuration
1) XML configuration
1 <!--target Bean that matches the tangent point -2 <BeanID= "Waiter"class= "Com.smart.aop.advice.pointcut.Waiter" />3 4 <!--Slice classes labeled with @aspectj -5 <Beanclass= "Com.smart.aop.advice.aspectj.PreGreetingAspect" />6 7 <!--automatic proxy Creator, capable of automatically weaving the facets of a @aspectj callout into the target bean -8 <Beanclass= "Org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator" />
2) Testing
1 PackageCOM.SMART.AOP.ADVICE.ASPECTJ;2 3 ImportOrg.springframework.context.ApplicationContext;4 ImportOrg.springframework.context.support.ClassPathXmlApplicationContext;5 Importorg.testng.annotations.Test;6 7 ImportCom.smart.aop.advice.pointcut.Waiter;8 9 Public classSpringaspectjtest {Ten One A @Test - Public voidbeforetest () { - the -ApplicationContext CTX =NewClasspathxmlapplicationcontext ("Classpath:com/smart/aop/advice/aspectj/beans-aspectj.xml"); -Waiter waiter = Ctx.getbean ("Waiter", waiter.class); - +Waiter.greetto ("Jack"); -Waiter.serverto ("Jack"); + } A}
Spring AspectJ Example