1. 程式人生 > >service層實現類serviceImpl單元測試,報錯org.springframework.beans.factory.UnsatisfiedDependencyException,報代理錯誤

service層實現類serviceImpl單元測試,報錯org.springframework.beans.factory.UnsatisfiedDependencyException,報代理錯誤

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.microboy.demo.service.Impl.AreaServiceImplTest': Unsatisfied dependency expressed through field 'areaServiceImpl'; 

nested exception is org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'areaServiceImpl' is expected to be of type 'com.microboy.demo.service.Impl.AreaServiceImpl' but was actually of type 'com.sun.proxy.$Proxy75'

這個錯誤的根本原因看最後,在使用annotation(註解)的方式注入spring的bean 時,spring採用代理的機制導致的

    方案一:由於AreaServiceImpl 是一個實現類,使用JDK的動態代理不能注入,jdk的動態代理不支援類的注入,只支援介面方式注入,如果確時不想用spring提供的動態代理,則此時可以選擇用cglib代理解決。必須引入cglib的外部包

   方案二:JDK的動態代理需要的是介面方式注入,那就將上面的注入型別修改為介面如下