Bean named 'rateBoardService' is expected to be of type 'xxxx'

今天在写一个测试用例的时候遇到个Bug,提示语如下:

可以只看第一行

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.joinpay.cb.service.rate.service.RateBoardServiceTest': Unsatisfied dependency expressed through field 'rateBoardService'; 
nested exception is org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'rateBoardService' is expected to be of type 'com.joinpay.cb.service.rate.service.RateBoardService'
 but was actually of type 'com.sun.proxy.$Proxy69'

	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588)
	at ......

查阅了网上的资料,发现有两种答案

1、用实现类接收注入

2、AOP切面中,使用jdk的动态代理注入还是CGLib动态代理技术织入增强

解决方法

1、本身是一个service项目,不存在切面,因此排除了第二种。

在注入实例的时候使用了具体的实现类去接收,导致这个问题出现

@Transactional
public class RateBoardServiceTest extends SpringJunitSupport {
    /***
     * RateBoardService 是具体的实现类,非接口
     */
    @Autowired
    private RateBoardService rateBoardFacade;

    public RateBoard getRateBoard(){
        RateBoard rateBoard = new RateBoard();
        rateBoard.setCurtypeFrom("844");
        rateBoard.setCurtypeTo("036");
        rateBoard.setBankType("1001");
        return rateBoard;
    }

    @Test
    @Rollback(value = false)
    public void testCreate(){
        RateBoard rateBoard = this.getRateBoard();
        assertEquals(true, rateBoardFacade.saveRateBoard(rateBoard));
    }
}

然后修改为接口接收

    @Autowired
    private RateBoardFacade rateBoardFacade;

这时就不会报错了。

心得:

第一次遇到这个问题,看网上博文说,CGLIB代理还是JDK代理一脸懵逼。

这时候要区分两种情况。如果说是web项目,对外有切面的配置,才要去检查CGLIB代理还是JDK动态代理

而且如果不是新项目的话,别人的测试用例没有问题,而你的测试用例有问题,考虑一下第一种情况。

希望对你们有帮助

 

下一篇,有空详细说一下CGLIB代理和JDK代理区别

 

 

 

 

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐