Spring DI表达不满意的依赖性

时间:2012-09-19 07:22:52

标签: spring model-view-controller servlets dependency-injection inversion-of-control

的applicationContext.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="user" class="com.pomkine.pottyauth.domain.User"/>
    <bean id="userdao" class="com.pomkine.pottyauth.persistance.GaeUserDao"/>
    <bean id="userservice" class="com.pomkine.pottyauth.service.UserServiceImpl">
        <constructor-arg ref="userdao"/>
    </bean>
</beans>

控制器:

@Controller
public class RosterController {

    private UserService userService;

    @Inject
    public RosterController(UserService userService){
        this.userService=userService;
    }

    @RequestMapping(value = {"/userRoster"}, method = RequestMethod.GET)
    public String showRosterPage(Map<String,Object> model){
        model.put("users",userService.getAllUsers());
        return "userRoster";
    }
}

所以我希望将UserService注入我的控制器。但我得到以下例外:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'rosterController' defined in file [S:\Coding\Idea_workspace\pottyAuth\target\pottyAuth-1.0\WEB-INF\classes\com\pomkine\pottyauth\mvc\RosterController.class]: Unsatisfied dependency expressed through constructor argument with index 0 of type [com.pomkine.pottyauth.service.UserService]: : No matching bean of type [com.pomkine.pottyauth.service.UserService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency.

这是我的UserServiceImpl类:

public class UserServiceImpl implements UserService {

    private UserDao dao;



    public UserServiceImpl(UserDao dao){
        this.dao=dao;
    }
    @Override
    public User getUser(User user) {
        return dao.getUser(user);
    }

    @Override
    public void addUser(User user) {
         dao.addUser(user);
    }

    @Override
    public List getAllUsers() {
        return dao.getAllUsers();
    }
}

所以我期待Spring容器创建UserServiceImlp bean并将其注入到RosterController中。但似乎找不到UserServiceImpl bean。

可能出现什么问题?

2 个答案:

答案 0 :(得分:0)

UserServiceImpl未实现UserService

编辑: 我也看不到

<context:component-scan  base-package="">

这是整个Spring的配置吗?

答案 1 :(得分:0)

这意味着Spring无法找到UserService类型的任何bean。检查您的UserServiceImpl课程 想知道为什么要使用基于XML和注释的方法来定义bean?如果你坚持他们中的任何一个都会很好。


修改
@Component注释添加到UserServiceImpl。这样Spring就会知道它应该创建一个UserServiceImpl

的对象
@Component
public class UserServiceImpl implements UserService  
{
.....  
}  

并且正如@pawelccb提到的那样使用

<context:component-scan  base-package="your.base.package">

在Spring配置文件中 有关详细信息,请查看此link