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