我是java spring-mvc当前的新手,我有一个@Controller调用@Repository,并且我想在@Repository中使用@Service,这是可能的还是正确的方法?
我试过将服务放入存储库中
@RequestMapping(value = "/activa-servicio", params={"cupon"}, method = RequestMethod.POST, produces = {MediaType.APPLICATION_JSON_VALUE})
@ResponseBody
public String activaServicio(HttpServletRequest request,@RequestParam(value="cupon") String cupon) throws IOException {
String json=publicDAO.activaServicio(cupon);
System.out.println(json);
return json;
}
@Repository
public class PublicDAO {
@Autowired
JdbcTemplate jdbcTemplate;
EmailService emailService;
public String activaServicio(String cupon) {
emailService.getActivationConfirmation();
}
我预计将触发EmailService,但是当前EmailService显示null异常
最佳答案
EmailService
为空,因为您从未设置它。 @Autowired
注释仅适用于JdbcTemplate jdbcTemplate
。
另外,不建议使用字段注入,因此最好的选择是使用构造函数注入。它也不太冗长。
private JdbcTemplate template;
private EmailService service;
@Autowired
public PublicDao(JdbcTemplate jt, EmailService es) {
this.template = jt;
this.service = es;
}