在Spring MVC中,我有models.UserDAO
课程:
@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
这个controllers.UserController
课程:
@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
到目前为止一切正常:用户通过UserDAO保存方法正确保存在数据库中。
现在我实现了另一个控制器controllers.MainController
:
@Controller
public class MainController {
@Autowired
private ApplicationContext _appContext;
@RequestMapping(value="/user")
public String profile()
// ...
UserDAO userDao = _appContext.getBean(UserDAO.class);
// ...
}
} // class MainController
在后一个控制器中,我收到Bean时遇到错误:No qualifying bean of type [myproject.models.UserDAO] is defined
可能是我得到bean的错误?:
_appContext.getBean(UserDAO.class);
修改
我试图在我的JavaConfig中添加它:
@Bean
public UserDAO userDao(){
return new UserDAO();
}
我用UserDAO注入替换了ApplicationContext _appContext
自动装配:
@Autowired
private UserDAO userDao;
但现在我收到了这个错误:
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)}
答案 0 :(得分:0)
您是否在beans.xml中设置了UserDAO类(或等效的JavaConfig类取决于您在应用程序中使用的类)?
为什么不将UserDAO实例本身注入控制器?在我看来,您目前正在应用服务定位器(反)模式。