.....
<!-- 配置解釋處理器 為@AspectJ注解提供支持 -->
<aop:aspectj-autoproxy />
.....
<beans>
(2)
<bean id="myInterceptor" class="com.hf.service.impl.MyInterceptor"></bean>
<bean id="personService" class="com.hf.service.impl.PersonServiceBean" ></bean>
將切面和被攔截的類交給spring管理
(3)切面類
@Aspect //定義切面類
public class MyInterceptor {
/**
* @Pointcut("execution(* com.hf.service..*.*(..))")表達(dá)式含義
* 第一個(gè)* 表示返回值類型為任意類型
* com.hf.service.. 兩個(gè)點(diǎn)表示包路徑下的子包的類也要攔截
* com.hf.service..*.* 子包的所有類中的所有方法 第一個(gè)*是方法第二個(gè)*是類
* (..)代表方法參數(shù)隨意 可有可無可多可少
* **/
@Pointcut("execution (* com.hf.service.impl.PersonServiceBean.*(..))")// 定義切入點(diǎn)
private void andMethod()//聲明一個(gè)切入點(diǎn)
{}
/* @Before("andMethod()")
public void doAccessCheck(){
System.out.println("前置通知");
}
*/
@Before("andMethod() && args(name)") //帶參數(shù) 只攔截符合參數(shù)類型的方法
public void doAccessCheck(String name){
System.out.println("前置通知"+name);
}
/* @AfterReturning("andMethod()")
public void doFaterReturning(){
System.out.println("后置通知");
}*/
@AfterReturning(pointcut="andMethod()",returning="result")//帶返回值的 無返回值的方法 result為null
public void doFaterReturning(String result){//攔截方法執(zhí)行后 獲取返回值對象
System.out.println("后置通知:"+result);
}
@After("andMethod()")
public void doAfter(){
System.out.println("最終通知");
}
/* @AfterThrowing("andMethod()")
public void doAfterThrowing(){
System.out.println("例外通知");
}*/
@AfterThrowing(pointcut="andMethod()" , throwing="e") //獲取例外并打印
public void doAfterThrowing(Exception e){
System.out.println("例外通知:"+e);
}
@Around("andMethod()")//環(huán)繞通知
public Object doBasecProfiling(ProceedingJoinPoint pjp )throws Throwable{
//if(){//判斷是否與權(quán)限
System.out.println("進(jìn)入通知");
Object result = pjp.proceed();
System.out.println("離開 通知");
//}
return result;
}
}
(4)業(yè)務(wù)類 PersonServiceBean
public class PersonServiceBean implements PersonService {
public void save(String name){
throw new RuntimeException("純屬例外");
// System.out.println("我是Save方法"+name);
}
public String update() {
return "我是update方法";
}
}