问题描述:
错误信息:Caused by: org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'IDepartmentServiceImpl' is expected to be of type 'cn.yue.service.impl.IDepartmentServiceImpl' but was actually of type 'com.sun.proxy.$Proxy26'
at org.springframework.beans.factory.support.DefaultListableBeanFactory.checkBeanNotOfRequiredType(DefaultListableBeanFactory.java:1524)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1502)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1101)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1062)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:583)
... 27 more
原因分析:
在使用Spring配置时,@Service注解标注在实现类上,@Service将会把spring容器中的bean进行实例化,也就是等同于new操作,只有实现类是可以进行new实例化,而接口则不能,故加在实现类上。 @Autowired注解是标注在接口上的,Spring将会按 byType的方式寻找接口的实现类,将其注入。存在多个实现类,需要指定名字,通过 byName 注入的方式。使用 @Resource 或 @Qualifier 注解。
@Service
public class IDepartmentServiceImpl implements IDepartmentService {
private DepartmentMapper departmentMapper;
@Autowired
public void setDepartmentMapper(DepartmentMapper departmentMapper) {
this.departmentMapper = departmentMapper;
……
}
}
——————————————————————————————Cutting line————————————————————————————————————————————
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class DepartmentServiceTest {
@Autowired
private IDepartmentServiceImpl departmentService;
……
}
}
解决方案:
将测试类中 @Autowired标注的实现类换成实现的接口
@Autowired
private IDepartmentServiceImpl departmentService;
——————————————————————————————Cutting line————————————————————————————————————————————
@Autowired
private IDepartmentService departmentService;