【问题标题】:Could not autowire field, but I have the definition无法自动装配字段,但我有定义
【发布时间】:2011-03-17 17:03:42
【问题描述】:

我的 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. 如果我不执行自动装配,我会做什么而不是在 UserDao 定义中添加 @AutoWire。

【问题讨论】:

    标签: java hibernate spring spring-mvc


    【解决方案1】:

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

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

    【讨论】:

    • 好的,我没有实现 UserDao 啊!谢谢!顺便说一句,你如何通过调试读取spring的引导日志或内存?)这些都是我应该学习的好技能!
    • 我已经更新了关于日志记录和调试的答案。 :)
    猜你喜欢
    • 2016-02-23
    • 1970-01-01
    • 2023-03-13
    • 2016-03-23
    • 1970-01-01
    • 1970-01-01
    • 2014-02-26
    • 2016-04-15
    • 2014-10-07
    相关资源
    最近更新 更多