Spring框架中aop动态代理踩的坑

Spring框架中aop动态代理踩的坑

这里我随便定义了一个接口和一个实现类作为被代理对象

public interface Calculator {
    public Integer add(Integer i, Integer j);
    public Integer sub(Integer i, Integer j);
    public Integer mul(Integer i, Integer j);
    public Integer div(Integer i, Integer j);
}
import org.springframework.stereotype.Component;

@Component
public class MyCalculator implements Calculator{

    @Override
    public Integer add(Integer i, Integer j) {
        return i+j;
    }

    @Override
    public Integer sub(Integer i, Integer j) {
        return i-j;
    }

    @Override
    public Integer mul(Integer i, Integer j) {
        return i*j;
    }

    @Override
    public Integer div(Integer i, Integer j) {
        return i/j;
    }
}

这是定义的切面类

package com.zc.util;


import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class LogUtil {

    @Before("execution(public Integer com.zc.proxy.MyCalculator.add(Integer,Integer))")
    public static void start(){
        System.out.println("start.......");
    }

    @After("execution(public Integer com.zc.proxy.MyCalculator.add(Integer,Integer))")
    public static void end(){
        System.out.println("end.........");
    }

}

下面是单元测试

@Test
public void test02(){
    MyCalculator myCalculator = applicationContext.getBean("myCalculator", MyCalculator.class);
    myCalculator.add(1,2);
}

这里由于经验不足调试了半天,因为默认aspectj使用的jdk提供的动态代理,必须要求被代理类需要实现接口,这里我是实现了接口,但是我在单元测试的时候,调用getBean方法我传入的是接口的实现类,于是就会报这样一个错误

org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'myCalculator' is expected to be of type 'com.zc.proxy.MyCalculator' but was actually of type 'com.sun.proxy.$Proxy17'

可以看到类的类型对应不上,当换成接口类后,运行成功~~~哈哈哈

@Test
public void test02(){
    Calculator myCalculator = applicationContext.getBean("myCalculator", Calculator.class);
    myCalculator.add(1,2);
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值