spring ----> aop的兩種實現方式
阿新 • • 發佈:2018-02-14
select imp ack exe readv expr gpo for public
實現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"/>
測試結果:
spring ----> aop的兩種實現方式