实现1:基于xml
package com.rr.spring3.interf; //接口 public interface SayHello { public void sayHello(); }
package com.rr.spring3.interf.impl; //接口实现类 import com.rr.spring3.interf.SayHello; public class Hello implements SayHello { public void sayHello() { System.out.println("hello"); } }
package com.rr.spring3.aop;//切面类+通知 public class HelloAspect { // 前置通知 public void beforeAdvice() { System.out.println("===========before advice"); } // 后置最终通知 public void afterFinallyAdvice() { System.out.println("===========after finally advice"); } }
<!-- 目标类 --> <bean id="hello" class="com.rr.spring3.interf.impl.Hello"/> <!-- 切面类 --> <bean id="helloAspect" class="com.rr.spring3.aop.HelloAspect"/> <aop:config> <!-- 引用切面类 --> <aop:aspect ref="helloAspect"> <!-- 切入点 --> <aop:pointcut id="pc" expression="execution(* com.rr.spring3.interf.*.*(..))"/> <!-- 引用切入点 ,指定通知--> <aop:before pointcut-ref="pc" method="beforeAdvice"/> <aop:after pointcut="execution(* com.rr.spring3.interf.*.*(..))" method="afterFinallyAdvice"/> </aop:aspect> </aop:config>
实现2:基于java5 注解 @Aspect
接口和接口实现类同上
package com.rr.spring3.aop; //切面类+通知 import org.aspectj.lang.annotation.After; //基于 java5 注解 import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; @Aspect public class HelloAspect { @Pointcut("execution(* com.rr.spring3.interf.*.*(..))") private void selectAll() {} // 前置通知 @Before("selectAll()") public void beforeAdvice() { System.out.println("===========before advice"); } // 后置最终通知 @After("selectAll()") public void afterFinallyAdvice() { System.out.println("===========after finally advice"); } }
<aop:aspectj-autoproxy/> <!-- 开启注解 --> <!-- 目标类 --> <bean id="hello" class="com.rr.spring3.interf.impl.Hello"/> <!-- 切面类 --> <bean id="helloAspect" class="com.rr.spring3.aop.HelloAspect"/>
测试结果:
note:
v1.0.1:
①第二种方法是aspectjweaver jar包的注解