0

应用程序上下文.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。

有什么问题?

4

2 回答 2

0

UserServiceImpl 没有实现 UserService

编辑:我也看不到

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

这是整个 Spring 配置吗?

于 2012-09-19T07:29:25.193 回答
0

这意味着 Spring 找不到任何类型的 bean UserService。检查你的UserServiceImpl班级。
想知道为什么要同时使用基于 XML 和注释的方法来定义 bean?如果你坚持其中任何一个,那就太好了。


编辑:
@Component注释添加到UserServiceImpl. 这样Spring就会知道它应该创建一个对象UserServiceImpl

@Component
public class UserServiceImpl implements UserService  
{
.....  
}  

正如@pawelccb 提到的那样使用

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

在 Spring 配置文件中。
检查此链接以获取详细信息。

于 2012-09-19T08:38:07.303 回答