SpringMVC 错误分析:@Autowired Could not autowire field

来源:互联网 发布:java web项目面试题 编辑:程序博客网 时间:2024/06/01 10:48

http://blog.sina.com.cn/s/blog_4e64ae7a0106grdp.html

在开发SpringMVC中碰到了组件不能@Autowired的错误,以前好像也碰到过,怎么解决的忘记了,今天记在这里。可供碰到同样问题的朋友参考。


下面是Controller组件:
@Controller
public class ManageUserController {
    private UserService userService;
   
    @Autowired   //此处自动注入userService
    public void setUserService(UserService userService) {
        this.userService = userService;
    }
   .....
}

其中Service组件为:
@Transactional
@Service("userService")
public class UserService implements UserServiceInf {
    private UserDao userDao;
   
   
    @Autowired
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

   
    public void createUser(User user) {
        this.userDao.createUser(user);
    }
  ....
}

运行系统后总是出现userService不能autowired注入的错误。 费了半天劲,最后总是解决了。Spring的注入基于接口实现,基于接口的方式一是可以使得各个组件松耦合,而且也可以轻松的替代某一组件。
所以应该讲组件引用改为接口方式。
Controller组件中的userService组件应
由:private UserService userService;
改为: private UserServiceInf userService;

同理Service组件中的userDao组件应
由: private UserDao userDao;
改为: private UserDaoInf userDao;
0 0