无法自动装配字段,但我有定义

时间:2010-07-19 00:49:37

标签: java hibernate spring spring-mvc

我的app-config.xml有我的UserDao bean的定义:

  <bean id="userDao" class="com.blah.core.db.hibernate.UserDaoImpl">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>

我有我的组件扫描:

<context:component-scan base-package="com.blah" />

我的HomeController中的索引操作正常(它将我的UserService上的方法内容输出到freemarker模板)。

@Controller
public class HomeController {

    @Autowired
    private UserService userService;




    @RequestMapping("/")
    public ModelAndView Index() {



        ModelAndView mav = new ModelAndView();

        mav.setViewName("index");
        mav.addObject("message", userService.sayHello());

        mav.addObject("username", userService.getTestUser());


        return mav;
    }

'getTestUser()'是一个引用UserDao的新方法,它看起来像:

@Service
public class UserServiceImpl implements UserService{

    @Autowired
    UserDao userDao;

    public String sayHello() {

        return "hello from user service impl part 2";

    }

    public String getTestUser() {


        return userDao.getById(1L).getUsername();

    }


}

我收到错误:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userServiceImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.blah.core.db.hibernate.UserDao com.blah.core.services.UserServiceImpl.userDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.blah.core.db.hibernate.UserDao] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
  1. 问题是什么?
  2. 如果我没有做autowire,我会做什么而不是在UserDao定义中添加@AutoWire。

1 个答案:

答案 0 :(得分:15)

您是否尝试导出Spring的所有已注册bean(或通过Spring's bootstrap log读取debugging或内存)以查明userDao bean是否在列表中。请确保UserDaoImpl确实正在实施UserDao - 我正在指出这一点,因为我在这里没有看到UserDaoImpl的片段。

如果您不使用@Autowired,替代方法将通过ApplicationContext的getBean()显式获取bean的引用(这被认为是一种肮脏的方式,而是修复您的@Autowired) ,通过其bean名称,类名等。