Spring AOP中使用事务管理注解@Transactional出现错误BeanNotOfRequiredTypeException

267 阅读1分钟

解决出现的BeanNotOfRequiredTypeException问题

刚开始以为是Spring AOP中动态代理的两种模式出现的错误,一直再翻看两者之间区别,但是看了很多资料,发现出现的问题和JDK动态代理以及CGlLIB动态代理中出现的一些问题不匹配。当然还和两者之间动态代理机制有关联的

出现BeanNotOfRequiredTypeException的原因是:在测试,通过getBean()获取IOC容器中的对象出现错误

ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
AccountServiceImpl accountService = context.getBean("accountService", AccountServiceImpl.class);
@Service
@Transactional //事务注解
public class AccountServiceImpl implements AccountService {
}

分析:

 1. 因为AOP默认情况使用的是JDK动态代理,而JDK动态代理是面向接口的
     2. 在上述代码中getBean中accountService是代理对象,AccountServiceImpl是AccountService接口的实现类

解决: 通过getBean()获取获取对象时,获取接口类型的

ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
AccountService accountService = context.getBean("accountService", AccountService.class);