问题描述
在网上看到这样一句话:“把DAO实现类注入到service实现类中,把service的接口(注意不要是service的实现类)注入到action中”,确实如此,比如UserServiceImpl实现了接口UserService,当我在UserAction中写private UserServiceImpl userService;@Resourcepublic void setUserService(UserServiceImpl userService) {this.userService = userService;}会报错。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中注入接口正确,但是注入实现类不行,能不能讲讲为什么啊 问题补充:zyn010101 写道
解决方案
因为代理的原因,注入的是一个代理类,不能转型成UserServiceImpl,所以set会报错。而接口肯定不会报错
解决方案二:
UserAction 里面注入 UserService在配置文件中,(不管是注释还是手写)都会有这么一行<bean id="UserAction" class="UserAction"><property name="userService" ref="userService" /></bean><bean id="userService" class="UserServiceImpl"/>因此 注入方式是property name,要与setXxx): private UserService userService; public void setUserService(UserService userService) { this.userService = userService; } 因此配置文件是这样也是可以的:<bean id="UserAction" class="UserAction"><property name="service" ref="userService" /></bean> 就需要写成 private UserService service; public void setService(UserService userService) { this.service = userService; } 而你的方式,setUserService(UserServiceImpl userService)配置文件应该如下,让spring去寻找 bean为 userServiceImpl的id<bean id="UserAction" class="UserAction"><property name="service" ref="userService" /></bean><bean id="userServiceImpl" class="UserServiceImpl"/>
解决方案三:
private UserService userService; @Resource public void setUserService(UserService userService) { this.userService = userService; } public UserService getUserService(){ return this.userService}在spring中这么配置<bean id="userService" class="UserServiceImpl"/>