在Spring MVC项目中,我有一个DAO类myproj.models.UserDAO
:
@Repository
@Transactional
public class UserDAO {
// UserDAO methods ...
}
我应该在控制器中使用它,比如myproj.controllers.UserController
:
@Controller
public class UserController {
// UserController methods ...
@RequestMapping(value="/{user}")
public String create(String user) {
// Here I want to use the UserDAO
// ...
}
}
如何创建UserDAO对象的实例并在控制器方法中使用它?
答案 0 :(得分:5)
您可以尝试以下
@Repository
@Transactional
public class UserDAO {
// UserDAO methods ...
}
控制器:
@Controller
public class UserController {
@Autowired //this will give you the reference to UserDAO
UserDAO userDao;
// UserController methods ...
@RequestMapping(value="/{user}")
public String create(String user) {
// Here I want to use the UserDAO
userDao.userDaoMethod();
// ...
}
}
有关@Autowired explore this
的更多信息答案 1 :(得分:0)
用户Autowired
注释,用于注入DAO的bean实例:
@Controller
public class UserController {
@Autowired
UserDAO userDao;
@RequestMapping(value="/{user}")
public String create(String user) {
userDao.method();
}
}