views:

766

answers:

1

My app-config.xml has a definition for my UserDao bean:

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

I have my component scanning:

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

My index action in my HomeController works fine (it outputs the contents of a method on my UserService to a freemarker template).

@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;
    }

The 'getTestUser()' is a new method that makes reference to UserDao, it looks like:

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

    }


}

I am getting the error:

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. What could the issue be?
  2. If I didn't do autowire, what would I be doing instead of adding the @AutoWire on the UserDao definition.
+3  A: 

Have you tried exporting all registered beans of Spring (or read Spring's bootstrap log or the memory via debugging) to find out if the userDao bean is in the list. Please make sure that UserDaoImpl is really implementing UserDao too - I am pointing at this because am not seeing the snippet of UserDaoImpl here.

If you do not use @Autowired, the alternative will be explicitly obtaining a reference of the bean through ApplicationContext's getBean() (which is considered as a dirty way, fix your @Autowired instead), via its bean name, class name, etc.

yclian
ok I wasn't implementing the UserDao ahh! thanks! btw, how do you read spring's bootstrap log or the memory via debugging?) Those are good skills I should learn!
Blankman
I have updated the answer with references to logging and debugging. :)
yclian