【发布时间】:2016-12-29 02:12:25
【问题描述】:
在同一请求中,我收到 NullPointerException 异常,而在另一部分代码则正常。
@Controller
@RequestMapping(value="/event")
public class EventController {
@Autowired
EventValidator eventValidator;
@Autowired
private EventService eventService;
@InitBinder
private void initBinder(WebDataBinder binder) {
System.out.println(eventValidator.toString()); <<—— NULL HERE
binder.setValidator(eventValidator);
}
@RequestMapping(value="/add_event",method = RequestMethod.POST,produces=MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public ResponseEntity<AjaxJSONResponse> postAddEventForm(@RequestPart("event") Event event, MultipartHttpServletRequest request,BindingResult result) throws MethodArgumentNotValidException, NoSuchMethodException
{
eventValidator.validate(event, result); <<——- OK HERE
//Check validation errors
if (result.hasErrors()) {
throw new MethodArgumentNotValidException(
new MethodParameter(this.getClass().getDeclaredMethod("postAddEventForm", Event.class, MultipartHttpServletRequest.class, BindingResult.class), 0),
result);
}
Boolean inserted = eventService.addEvent(event);
String contextPath = request.getContextPath();
String redirectURL = StringUtils.isEmpty(contextPath)?"/event":contextPath+"/event";
return new ResponseEntity<AjaxJSONResponse>(new AjaxJSONResponse(inserted,"Event Added Successfully",redirectURL), HttpStatus.OK);
}
}
在同一个请求中,initBinder() 函数中的 eventValidator 为 NULL,而 postAddEventForm() 函数中的 eventValidator 正在持有实例。
请帮忙。
【问题讨论】:
-
尝试将initBinder方法的作用域改为public。
-
谢谢 Chirdeep。您能否提供一个简短的信息,这就是我们需要公开的原因。
标签: spring spring-mvc autowired