天天看點

使用spring注解方式實作AOP(二)

如果需要對業務方法中的參數和傳回值做處理的情況下:

package com.chris.aop;

import org.springframework.stereotype.Service;

@Service("testService")
public class TestServiceBean {
	
	public void save(){
		System.out.println("save...");
	}
	
	public String update(String string){
		System.out.println("update...");
		return string;
	}
	public void add(String name,int age){
		System.out.println("add..." +name+"-"+age);
	}
}
           

 切面類:

package com.chris.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Component//一定要将該類交給spring容器管理
@Aspect//聲明該類為一個切面
public class InterceptorDemo {

	//定義切入點(該切入點針對TestServiceBean中的所有方法進行攔截),切入點的文法下面介紹
	@Pointcut("execution(* com.chris.aop.TestServiceBean.*(..))")
	private void allMethod(){};//切入點的名稱就是方法名
	
	@Before("allMethod() && args(name,sex)")//定義切入點allMethod()中方法參數為(String,int)的方法的前置通知
	public void doSomethingBefore(String name,int sex){
		System.out.println("前置通知...");
	}
	
	@After("allMethod()")//定義切入點allMethod()的後置通知
	public void doSomethingAfter(){
		System.out.println("後置通知...");
	}
	
	@AfterReturning(pointcut="allMethod()",returning="update")//定義切入點allMethod()中傳回值為String的方法的最終通知
	public void doSomethingFinally(String update){
		System.out.println("最終通知..."+update);
	}
	
	@AfterThrowing(pointcut="allMethod()",throwing="ex")//定義切入點allMethod()中抛出Exception異常的方法的異常通知
	public void doSomethingInEx(Exception ex){
		System.out.println("異常通知...");
	}
	
	@Around("allMethod()")//定義切入點allMethod()的環繞通知,環繞通知方法一定要按照下面的形式定義(隻可以修改方法名和參數名)
	public Object doSomethingAround(ProceedingJoinPoint pjp) throws Throwable{
		System.out.println("進入環繞通知...");
		Object result = pjp.proceed();
		System.out.println("退出環繞通知...");
		return result;
	}
}