JoinPoint和ProceedingJoinPoint区别

5 篇文章 0 订阅

本文主要介绍JoinPoint的常用方法

原文链接:JoinPoint和ProceedingJoinPoint有啥不一样?

在以一个实际例子演示如何使用注解实现AOP装配时,为了监控应用程序的性能,我们定义一个性能监控的注解

@Target(METHOD)
@Retention(RUNTIME)
public @interface MetricTime {
    String value();
}

在需要被监控的关键方法上标注该注解:

@Component
public class UserService {
    // 监控register()方法性能:
    @MetricTime("register")
    public User register(String email, String password, String name) {
        ...
    }
    ...
}

然后,我们定义MetricAspect

@Component
@Aspect
public class MetricAspect {

    @Around("@annotation(metricTime)")
    public Object metric(ProceedingJoinPoint joinPoint,MetricTime metricTime) throws Throwable {
        String name = metricTime.value();
        Long startTime = System.currentTimeMillis();
        try{
//            System.out.println("joinPoint.proceed():  " + joinPoint.proceed());//com.sun.service.User@c055c54
            return joinPoint.proceed(new Object[]{"44444@163.com","dd23423dd","dddd"});
        }finally {
            long time = System.currentTimeMillis() - startTime;
            System.err.println("[Metrics] " + name + ": " + time + "ms");
        }

    }
}

注意metric()方法标注了@Around("@annotation(metricTime)"),它的意思是,符合条件的目标方法是带有@MetricTime注解的方法,因为metric()方法参数类型是MetricTime(注意参数名是metricTime不是MetricTime),我们通过它获取性能监控的名称。

有了@MetricTime注解,再配合MetricAspect,任何Bean,只要方法标注了@MetricTime注解,就可以自动实现性能监控。

@AppConfig.java

@ComponentScan
@Configuration
@EnableAspectJAutoProxy
public class AppConfig {

    public static void main(String[] args) throws Exception {
        ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
        UserService userService = (UserService) context.getBean("userService");
        User user = userService.register("333333333@qqqqq.com", "3333333qqaaa", "qqa333");
        System.out.println(user);
        }

运行结果:

mail service zoneId is init....Asia/Shanghai
i = 1
执行成功...
Welcome, dddd!
[Metrics] register: 612ms
User{id=92, email='44444@163.com', password='dd23423dd', name='dddd'}

数据库结果:

数据库

最终存储到数据库中的并不是:

User user = userService.register("333333333@qqqqq.com", "3333333qqaaa", "qqa333");

而是metric方法中:

@Around("@annotation(metricTime)")
    public Object metric(ProceedingJoinPoint joinPoint,MetricTime metricTime) throws Throwable {
        String name = metricTime.value();
        Long startTime = System.currentTimeMillis();
        try{
//            System.out.println("joinPoint.proceed():  " + joinPoint.proceed());//com.sun.service.User@c055c54
             return joinPoint.proceed(new Object[]{"44444@163.com","dd23423dd","dddd"}); 
        }finally {
            long time = System.currentTimeMillis() - startTime;
            System.err.println("[Metrics] " + name + ": " + time + "ms");
        }

    }

return joinPoint.proceed(new Object[]{"44444@163.com","dd23423dd","dddd"});


研究一下JoinPoint方法的使用

AspectJ使用org.aspectj.lang.JoinPoint接口表示目标类连接点对象,如果是环绕增强时,使用org.aspectj.lang.ProceedingJoinPoint表示连接点对象,该类是JoinPoint的子接口。任何一个增强方法都可以通过将第一个入参声明为JoinPoint访问到连接点上下文的信息。我们先来了解一下这两个接口的主要方法:

JoinPoint

JoinPoint

JoinPoint对象封装了SpringAop中切面方法的信息,在切面方法中添加JoinPoint参数,就可以获取到封装了该方法信息的JoinPoint对象,常用api:

方法名功能
Signature getSignature()获取封装了署名信息的对象,在该对象中可以获取到目标方法名,所属类的Class等信息
Object[] getArgs()获取传入目标方法的参数对象
Object getTarget()获取被代理的对象
Object getThis()获取代理对象

ProceedingJoinPoint

ProceedingJoinPoint对象是JoinPoint的子接口,该对象只用在@Around的切面方法中, 添加了两个方法.

方法名功能
Object proceed() throws Throwable执行目标方法
Object proceed(Object[] var1) throws Throwable传入的新的参数去执行目标方法

Demo

切面类:

@Aspect
@Component
public class aopAspect {
    /**
     * 定义一个切入点表达式,用来确定哪些类需要代理
     * execution(* aopdemo.*.*(..))代表aopdemo包下所有类的所有方法都会被代理
     */
    @Pointcut("execution(* aopdemo.*.*(..))")
    public void declareJoinPointerExpression() {}
 
    /**
     * 前置方法,在目标方法执行前执行
     * @param joinPoint 封装了代理方法信息的对象,若用不到则可以忽略不写
     */
    @Before("declareJoinPointerExpression()")
    public void beforeMethod(JoinPoint joinPoint){
        System.out.println("目标方法名为:" + joinPoint.getSignature().getName());
        System.out.println("目标方法所属类的简单类名:" +        joinPoint.getSignature().getDeclaringType().getSimpleName());
        System.out.println("目标方法所属类的类名:" + joinPoint.getSignature().getDeclaringTypeName());
        System.out.println("目标方法声明类型:" + Modifier.toString(joinPoint.getSignature().getModifiers()));
        //获取传入目标方法的参数
        Object[] args = joinPoint.getArgs();
        for (int i = 0; i < args.length; i++) {
            System.out.println("第" + (i+1) + "个参数为:" + args[i]);
        }
        System.out.println("被代理的对象:" + joinPoint.getTarget());
        System.out.println("代理对象自己:" + joinPoint.getThis());
    }
 
    /**
     * 环绕方法,可自定义目标方法执行的时机
     * @param pjd JoinPoint的子接口,添加了
     *            Object proceed() throws Throwable 执行目标方法
     *            Object proceed(Object[] var1) throws Throwable 传入的新的参数去执行目标方法
     *            两个方法
     * @return 此方法需要返回值,返回值视为目标方法的返回值
     */
    @Around("declareJoinPointerExpression()")
    public Object aroundMethod(ProceedingJoinPoint pjd){
        Object result = null;
 
        try {
            //前置通知
            System.out.println("目标方法执行前...");
            //执行目标方法
            //result = pjd.proeed();
            //用新的参数值执行目标方法
            result = pjd.proceed(new Object[]{"newSpring","newAop"});
            //返回通知
            System.out.println("目标方法返回结果后...");
        } catch (Throwable e) {
            //异常通知
            System.out.println("执行目标方法异常后...");
            throw new RuntimeException(e);
        }
        //后置通知
        System.out.println("目标方法执行后...");
 
        return result;
    }
}

被代理类:

/**
 * 被代理对象
 */
@Component
public class TargetClass {
    /**
     * 拼接两个字符串
     */
    public String joint(String str1, String str2) {
        return str1 + "+" + str2;
    }
}

测试类:

public class TestAop {
    @Test
    public void testAOP() {
        //1、创建Spring的IOC的容器
        ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:bean.xml");
 
        //2、从IOC容器中获取bean的实例
        TargetClass targetClass = (TargetClass) ctx.getBean("targetClass");
 
        //3、使用bean
        String result = targetClass.joint("spring","aop");
        System.out.println("result:" + result);
    }
}

测试结果:

目标方法执行前...
目标方法名为:joint
目标方法所属类的简单类名:TargetClass
目标方法所属类的类名:aopdemo.TargetClass
目标方法声明类型:public1个参数为:newSpring
第2个参数为:newAop
被代理的对象:aopdemo.TargetClass@4efc180e
代理对象自己:aopdemo.TargetClass@4efc180e
目标方法返回结果后...
目标方法执行后...
result:newSpring+newAop

Q&A

Q: 代理对象自己和被代理对象输出的内存地址一样啊楼主!应该就是这样的吗?

A:不是,所谓代理类其实就是内部调用了目标类的方法,两个不同的对象内存地址不可能一样,上面的目标类和代理类打印调用的是toString(),但是代理类调用的其实是目标类的toString,所以地址一样,但是你如果用==比较是不一样的,也就是false

  • 6
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值