Failed to create autwire field, but I have a definition

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 a component scan:

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

My index action in my HomeController works great (it outputs the contents of the method in my UserService to the 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; } 

"getTestUser ()" is a new method that references UserDao, it looks like this:

 @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 get an error message:

 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)} 
  • What could be the problem?
  • If I did not autowire, what would I do instead of adding @AutoWire to the definition of UserDao.
+7
java spring spring-mvc hibernate
source share
1 answer

You tried to export all registered beans from Spring (or read Spring boot log or memory via debugging ) to find out if userDao bean is on the list. Please make sure that UserDaoImpl really implements userDao too - I point this out because I don’t see a fragment of UserDaoImpl here.

If you are not using @Autowired , the alternative would explicitly get a bean reference to ApplicationContext getBean () (which is considered dirty, fix @Autowired instead) using its bean name, class name, etc.

+15
source share

All Articles