本文介绍了Spring @Autowired bean给空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在同一请求中,一方面我得到了NullPointerException,另一方面在代码中也没关系.
In the same request at one part, I am getting NullPointerException and at other part of code it is ok.
@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
中包含该实例.
In same request, in initBinder()
function eventValidator
is NULL and in postAddEventForm()
function eventValidator
is holding the instance.
请对此提供帮助.
推荐答案
initBinder()
方法的访问说明应为public
-
Access specifier of initBinder()
method should be public
-
public void initBinder(WebDataBinder binder) {
这篇关于Spring @Autowired bean给空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!