前置增强
public class GreetingBeforeAdvice implements MethodBeforeAdvice{
@Override
public void before(Method method,Object[] args,Object target)throws Throwable{
System.out.println("Before");
}
}
后置增强
public class GreetingAfterAdvice implements AfterReturningAdvice{
@Override
public void afterReturning(Object result,Method method,Object[] args,Object target)throws Throwable{
System.out.println("After");
}
}
环绕增强
public class GreetingAroundAdvice implements MethodInterceptor{
@Override
public Object invoke(MethodInvocation invocation) throws Throwable{
before();
Object result = invocation.proceed();
after();
return result;
}
private void before(){
System.out.println("Before");
}
private void after(){
System.out.println("after");
}
}
抛出增强
public class GreetingThrowAdvice implements ThrowsAdvice{
public void afterThrowing(Method method,Object[] args,Object target,Exception e){
...
}
}
引入增强
public interface Apology{
void saySorry(String name);
}
public class GreetingIntroAdvice extends DelegatingIntroductionInterceptor implements Apology{
@Override
public Object invoke(MethodInvocation invocation)throws Throwable{
return super.invoke(invocation);
}
@Override
public void saySorry(String name){
System.println("Sorry!"+name);
}
}
使用
public class Client{
public static void main(String[] args){
ProxyFactory proxyFactory = new ProxyFactory();
proxyFactory.setTarget(new GreetingImpl());
proxyFactory.addAdvice(new GreetingBeforeAdvice());
proxyFactory.addAdvice(new GreetingAfterAdvice());
Greeting gteeting = (Greeting) proxyFactory.getProxy();
greeting.sayHello("Jack");
}
}