spring中aop的annotation的寫法
try{
業務代碼
后置通知
} catch{
異常通知
} finally{
最終通知
}
1.需要的jar包:aspectjrt.jar,aspectjweaver.jar,cglib-nodep-2.1.3.jar
2.在配置文件中加入
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=" xmlns:xsi=" xmlns:p=" xmlns:aop=" xmlns:tx=" xmlns:context=" xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
">
<!-- 讓spring支持annotation的aop -->
<aop:aspectj-autoproxy/>
<!-- 把切面類交給spring -->
<bean id="myAspece" class="com.yjw.aspect.MyAspect"/>
package com.yjw.aspect;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
//定義切面類,存放通知
@Aspect
public class MyAspect {
//切入點
/**第一個星號代表返回任何類型的數據,bean后的兩個點代表本包及其子包,
* 第二個星號代表中間的所有的類;
* 第三個星號代表中間的所有的方法;
* (..)小括號代表參數列表,兩個點代表參數類型不限
*/
@Pointcut("execution(* com.yjw.dao..*.*(..))")
public void pointCut(){}
//前置通知
@Before(" pointCut()")
public void beforeAdvice(){
System.out.println("前置通知");
}
//異常通知,接收異常信息
@AfterThrowing( pointcut=" pointCut()",throwing="ex")
public void exceptionAdvice(Exception ex){
System.out.println("異常出現"+ex.getMessage());
}
//后置通知,可以接收方法的返回值
@AfterReturning( pointcut=" pointCut()",returning="value")
public void afterReturningAdvice(Object value){
System.out.println("后置通知"+value);
}
//最終通知
@After(" pointCut()")
public void afterAdvice(){
System.out.println("zuizhong");
}