spring的依赖注入,为什么用接口的实现类而不是父类的继承类?

时间:2023-03-09 05:21:45
spring的依赖注入,为什么用接口的实现类而不是父类的继承类?

@Resource
private EmployeeService employeeService;

public void setEmployeeService(EmployeeService employeeService) {
this.employeeService = employeeService;
}

报错:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name '/login':

Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanNotOfRequiredTypeException:

Bean named 'employeeService' must be of type [com.xidian.service.imp.EmployeeService], but was actually of type [com.sun.proxy.$Proxy67]

改成接口方式:

@Resource
private EmployeeServiceInter employeeService;

public void setEmployeeService(EmployeeServiceInter employeeService) {
this.employeeService = employeeService;
}

就可以啦!

通常是service层需要aop。用接口的话,AOP可以使用java自带的动态代理,但是有点麻烦要写接口。用类就要用第三方包cglib,但是简单,不用写接口

jdk规定动态代理必须用接口;当然也可以用类,用cglib可以去处理就可以了。

相关文章