在网上看到这样一句话:“把DAO实现类注入到service实现类中,把service的接口([color=red]注意不要是service的实现类[/color])注入到action中”,确实如此,比如UserServiceImpl实现了接口UserService,当我在UserAction中写
[code="java"]
private UserServiceImpl userService;
@Resource
public void setUserService(UserServiceImpl userService) {
this.userService = userService;
}
[/code]
会报错。
Unable to instantiate Action, com.action.UserAction, defined for 'user' in namespace '/'Failed to convert property value of type [$Proxy25 implementing com.service.UserService,org.springframework.aop.SpringProxy,org.springframework.aop.framework.Advised] to required type [com.service.UserServiceImpl] for property 'userService'; nested exception is java.lang.IllegalArgumentException: Cannot convert value of type [$Proxy25 implementing com.service.UserService,org.springframework.aop.SpringProxy,org.springframework.aop.framework.Advised] to required type [com.service.UserServiceImpl] for property 'userService': no matching editors or conversion strategy found
把上面的类型改成UserService就ok了,经过多次测试,我采用的是注解方式配置,Service层一旦实现了接口,在action中注入接口正确,但是注入实现类不行,能不能讲讲为什么啊
因为代理的原因,注入的是一个代理类,不能转型成UserServiceImpl,所以set会报错。
而接口肯定不会报错
private UserService userService;
@Resource
public void setUserService(UserService userService) {
this.userService = userService;
}
public UserService getUserService(){
return this.userService
}
在spring中这么配置
UserAction 里面注入 UserService
在配置文件中,(不管是注释还是手写)都会有这么一行
因此 注入方式是property name,要与setXxx):
private UserService userService;
public void setUserService(UserService userService) {
this.userService = userService;
}
因此配置文件是这样也是可以的:
就需要写成
private UserService service;
public void setService(UserService userService) {
this.service = userService;
}
而你的方式,setUserService(UserServiceImpl userService)
配置文件应该如下,让spring去寻找 bean为 userServiceImpl的id