实现1:基于xml
1 package com.rr.spring3.interf; //接口 2 3 public interface SayHello { 4 5 public void sayHello(); 6 }
1 package com.rr.spring3.interf.impl; //接口实现类 2 3 import com.rr.spring3.interf.SayHello; 4 5 public class Hello implements SayHello { 6 public void sayHello() { 7 System.out.println("hello"); 8 } 9 10 }
1 package com.rr.spring3.aop;//切面类+通知 2 3 public class HelloAspect { 4 5 // 前置通知 6 public void beforeAdvice() { 7 System.out.println("===========before advice"); 8 } 9 10 // 后置最终通知 11 public void afterFinallyAdvice() { 12 System.out.println("===========after finally advice"); 13 } 14 15 }
1 <!-- 目标类 --> 2 <bean id="hello" class="com.rr.spring3.interf.impl.Hello"/> 3 <!-- 切面类 --> 4 <bean id="helloAspect" class="com.rr.spring3.aop.HelloAspect"/> 5 6 <aop:config> 7 <!-- 引用切面类 --> 8 <aop:aspect ref="helloAspect"> 9 <!-- 切入点 --> 10 <aop:pointcut id="pc" expression="execution(* com.rr.spring3.interf.*.*(..))"/> 11 <!-- 引用切入点 ,指定通知--> 12 <aop:before pointcut-ref="pc" method="beforeAdvice"/> 13 <aop:after pointcut="execution(* com.rr.spring3.interf.*.*(..))" method="afterFinallyAdvice"/> 14 </aop:aspect> 15 </aop:config>
实现2:基于java5 注解 @Aspect
接口和接口实现类同上
1 package com.rr.spring3.aop; //切面类+通知 2 3 import org.aspectj.lang.annotation.After; //java5 注解 4 import org.aspectj.lang.annotation.Aspect; 5 import org.aspectj.lang.annotation.Before; 6 import org.aspectj.lang.annotation.Pointcut; 7 8 @Aspect 9 public class HelloAspect { 10 11 @Pointcut("execution(* com.rr.spring3.interf.*.*(..))") 12 private void selectAll() {} 13 14 // 前置通知 15 @Before("selectAll()") 16 public void beforeAdvice() { 17 System.out.println("===========before advice"); 18 } 19 20 // 后置最终通知 21 @After("selectAll()") 22 public void afterFinallyAdvice() { 23 System.out.println("===========after finally advice"); 24 } 25 26 }
1 <aop:aspectj-autoproxy/> <!-- 开启注解 --> 2 <!-- 目标类 --> 3 <bean id="hello" class="com.rr.spring3.interf.impl.Hello"/> 4 <!-- 切面类 --> 5 <bean id="helloAspect" class="com.rr.spring3.aop.HelloAspect"/>
测试结果: