目标
package com.aop.joinpoint;
public class Greeting {
public void greet() {
System.out.print("World");
}
public String greetWithParam(String param) {
System.out.println("Param is " + param);
return param + ", nice to see you!";
}
}
环绕通知(又叫包围通知)
package com.aop.advice;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
public class AroundAdvice implements MethodInterceptor {
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
System.out.print("Hello ");
Object ret = invocation.proceed();
System.out.println("!");
return ret;
}
}
前置通知
package com.aop.advice;
import java.lang.reflect.Method;
import org.springframework.aop.MethodBeforeAdvice;
public class BeforeAdvice implements MethodBeforeAdvice {
@Override
public void before(Method method, Object[] arg, Object target) throws Throwable {
if (arg[0] == null) {
throw new IllegalArgumentException("arg cannot be null.");
}
System.out.println("Before method:" + method.getName() + "(\"" + arg[0] + "\")");
}
}
后置通知
package com.aop.advice;
import java.lang.reflect.Method;
import org.springframework.aop.AfterReturningAdvice;
public class AfterAdvice implements AfterReturningAdvice {
@Override
public void afterReturning(Object returningValue, Method method, Object[] arg, Object target) throws Throwable {
System.out.println("After method:" + method.getName() + "(\"" + arg[0] + "\")");
}
}
手动创建代理
package com.aop.demo;
import org.springframework.aop.framework.ProxyFactory;
import com.aop.advice.AfterAdvice;
import com.aop.advice.AroundAdvice;
import com.aop.advice.BeforeAdvice;
import com.aop.joinpoint.Greeting;
public class GreetingDemo {
public static void main(String[] args) {
Greeting target = new Greeting();
AroundAdvice aroundAdvice = new AroundAdvice();
BeforeAdvice beforeAdvice = new BeforeAdvice();
AfterAdvice afterAdvice = new AfterAdvice();
ProxyFactory pf = new ProxyFactory();
pf.addAdvice(aroundAdvice);
pf.setTarget(target);
Greeting proxy = (Greeting)pf.getProxy();
//不使用代理
target.greet();
System.out.println();
//使用代理(包围通用)
proxy.greet();
System.out.println();
pf.removeAdvice(aroundAdvice);
pf.addAdvice(beforeAdvice);
proxy = (Greeting)pf.getProxy();
//使用代理(前置通用)
System.out.println(proxy.greetWithParam("Bruce"));
System.out.println();
pf.removeAdvice(beforeAdvice);
pf.addAdvice(afterAdvice);
proxy = (Greeting)pf.getProxy();
//使用代理(后置通用)
System.out.println(proxy.greetWithParam("David"));
}
}
输出
/**Output:
World
Hello World!
Before method:greetWithParam("Bruce")
Param is Bruce
Bruce, nice to see you!
Param is David
After method:greetWithParam("David")
David, nice to see you!
*/