Spring项目出现BeanNotOfRequiredTypeException: Bean named ‘xxxImpl‘ is expected to be of type ‘xxx‘
运行spring项目时出现Caused by: org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'xxxImpl' is expected to be of type 'xyz.newtouch.service.impl.XxxImpl' but was actually of type 'com.sun.proxy.$Proxy666(非真实数值)'
,原因是自动注入时未正确编写注入时的变量修饰对象,例:需要从ioc中注入A接口的实例时未使用A接口来接收注入的内容,而使用了A接口的实现类来接收,伪代码如下:
public interface A {
}
@Component
class B implements A {
}
@ContextConfiguration(locations = "classpath:applicationContext.xml")
@RunWith(SpringJUnit4ClassRunner.class)
class XxxTest {
@Autowired
private B b;
@Test
public void test1() {
System.err.println(b);
}
}
此时应该使用A来修饰被注入的对象,因为存在接口时spring默认使用JDK动态代理,如果不存在接口才默认使用cglib动态代理(也可以直接指定全部使用cglib动态代理),cglib动态代理的情况下才可以直接使用实现类进行注入
还没有评论,来说两句吧...