Spring AOP 基本原理

前置增强

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");
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值