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

Bla*_*man 7 java spring hibernate spring-mvc

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

  <bean id="userDao" class="com.blah.core.db.hibernate.UserDaoImpl">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>
Run Code Online (Sandbox Code Playgroud)

我有我的组件扫描:

<context:component-scan base-package="com.blah" />
Run Code Online (Sandbox Code Playgroud)

我的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;
    }
Run Code Online (Sandbox Code Playgroud)

'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();

    }


}
Run Code Online (Sandbox Code Playgroud)

我收到错误:

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)}
Run Code Online (Sandbox Code Playgroud)
  1. 问题可能是什么?
  2. 如果我没有做autowire,我会做什么,而不是在UserDao定义上添加@AutoWire.

ycl*_*ian 15

您是否尝试导出Spring的所有已注册bean(或通过调试读取Spring的引导日志或内存)以确定bean是否在列表中.请确保这也是真正的实现- 我指的是这个,因为我没有看到这里的片段.userDaoUserDaoImplUserDaoUserDaoImpl

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