方法一:通過xml文件配置
xml配置如下:
<bean id="testAdvice" class="com.test.TestAdvice"></bean>
<aop:config>
<aop:aspect ref="testAdvice" >
<aop:after method="doLog" pointcut="execution(* com.service..*(..))" />
</aop:aspect>
</aop:config>
<aop:after>表示一個後置通知,也就是說要在切點執行後纔會執行通知;pointcut指明瞭切點位置;
<aop:aspect ref="testAdvice" >表示執行通知的bean;method="doLog" 表示執行通知的方法。
以上表示在切點執行後,就會執行testAdvice的doLog方法。
方法二:通過註解配置
1、配置註解
@Aspect
@Component("testAdvice")
public class TestAdvice {
@Before(value = "execution(* com.service..*(..))")
public void beforeLog(){
System.out.println("註解配置的通知");
}
}
@Component("testAdvice")定義一個名稱爲testAdvice的bean;@Aspect表示這是一個切面;@Before(value = "execution(* com.service..*(..))")表示這是一個前置通知,這個通知應用於切點value = "execution(* com.service..*(..))"
2、啓動以註解驅動的方式配置切面
<aop:aspectj-autoproxy ><aop:include name="testAdvice"/></aop:aspectj-autoproxy>
<aop:include name="testAdvice"/>表示把beanName爲testAdvice的bean當做一個切面,切面定義通知和切點。
aop實現原理
對於有通知的bean,會創建一個代理。 每一個通知都會被封裝成一個MethodInterceptor攔截器,在攔截器裏調用通知和連接點;比如前置通知攔截器MethodBeforeAdviceInterceptor,會首先調用通知,然後調用連接點。事物切面被封裝爲TransactionInterceptor。在請求bean的方法時,代理纔會去查找與該方法匹配的攔截器,形成一個攔截鏈。