在使用aop给UserServiceImpl增加日志功能的时候,测试时出现如下错误:
测试代码为:
public class MyTest {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserServiceImpl userService = context.getBean("userService", UserServiceImpl.class);
userService.add();
}
}
报错信息为Bean named ‘userService’ is expected to be of type ‘com.hj.service.UserServiceImpl’ but was actually of type ‘com.sun.proxy.$Proxy4’。
很显然,这里报错的原因是说我们getBean获取到的这个对象不是UserServiceImpl类的。
因为动态代理继承了Proxy类,而Java是单继承,不能再继承被代理类了,所以是基于接口的,实现了被代理类的接口。所以此处应该是用其接口类型,而不是实现类类型。而aop又是基于动态代理实现的,所以我们getbean获取到的代理对象实际上是实现了其接口类型的,而不是实现类类型的。
修改完如下:
public class MyTest {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
// 动态代理代理的是接口,所以这里直接UserService而不是UserServiceImpl
UserService userService = context.getBean("userService", UserService.class);
userService.add();
}
}