In Spring MVC I've this models.UserDAO
class:
@Repository
@Transactional
public class UserDAO implements UserDetailsService {
@Autowired
private SessionFactory _sessionFactory;
private Session getSession() {
return _sessionFactory.getCurrentSession();
}
public void save(User user) {
getSession().save(user);
return;
}
public User getById(long id) {
return (User) getSession().load(User.class, id);
}
@Override
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException {
// implementation
// ...
}
} // class UserDAO
And this controllers.UserController
class:
@Controller
public class UserController {
@Autowired
private ApplicationContext _appContext;
@RequestMapping(value="/users/create")
@ResponseBody
public String create(@RequestBody User user) {
// ...
UserDAO userDao = _appContext.getBean(UserDAO.class);
userDao.save(user);
// ...
}
} // class UserController
So far everything is working: the user is correctly saved in the db through the UserDAO save method.
Now I implemented another controller controllers.MainController
:
@Controller
public class MainController {
@Autowired
private ApplicationContext _appContext;
@RequestMapping(value="/user")
public String profile()
// ...
UserDAO userDao = _appContext.getBean(UserDAO.class);
// ...
}
} // class MainController
In this latter controller I've an error getting the Bean: No qualifying bean of type [myproject.models.UserDAO] is defined
Could be the error the way I get the bean?:
_appContext.getBean(UserDAO.class);
EDIT
I tried to add this in my JavaConfig:
@Bean
public UserDAO userDao(){
return new UserDAO();
}
and I replaced the ApplicationContext _appContext
autowired with the UserDAO injection:
@Autowired
private UserDAO userDao;
but now I get this error:
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mainController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private myproject.models.UserDAO myproject.controllers.MainController.userDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [myproject.models.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)}