手动AOP编程(ProxyFactory使用)

package com.aop;
 
import org.springframework.aop.AfterReturningAdvice;
import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.lang.Nullable;
 
import java.lang.reflect.Method;
 
public class AopTest {
 
    public static void main(String[] args) {
        AccountService target = new AccountService("张三", 10000D);
        //代理工厂(传入目标对象源,从中可以获取到目标对象)
        ProxyFactory proxyFactory = new ProxyFactory(new SingletonTargetSource(target));
        //前置通知
        proxyFactory.addAdvice(new MethodBeforeAdvice() {
            @Override
            public void before(Method method, Object[] args, @Nullable Object target) {
                System.out.println("【代理对象】开始调用...");
                String userName = (String) args[0];
                //用户校验
                if (!"张三".equals(userName)) {
                    throw new RuntimeException(String.format("用户%s无权访问!", userName));
                }
            }
        });
        //后置通知
        proxyFactory.addAdvice(new AfterReturningAdvice() {
            @Override
            public void afterReturning(@Nullable Object returnValue, Method method, Object[] args, @Nullable Object target) {
                System.out.println(method + ",执行完毕!");
                System.out.println("【代理对象】结束调用...");
                System.out.println();
            }
        });

		// spring aop中最常用的方法拦截器
		proxyFactory.addAdvice(new MethodInterceptor() {
            @Override
            public Object invoke(MethodInvocation invocation) throws Throwable {
                log.info("methodInterceptor enter...");
                log.info("methodInterceptor:{}", invocation.getMethod());
                log.info("methodInterceptor:{}", Arrays.toString(invocation.getArguments()));
                log.info("methodInterceptor:{}", invocation.getThis());
                log.info("methodInterceptor:{}", invocation.getStaticPart());
                Object result = invocation.proceed();
                System.out.println("methodInterceptor leave...");
                return result;
            }
        });
 
 
        //通过代理工厂创建代理
        AccountService proxy = (AccountService) proxyFactory.getProxy();
        //调用代理的方法
        proxy.add("张三", 100);
 
        proxy.reduce("李四", 100);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值