Spring @Autowired bean giving null

拜拜、爱过 提交于 2019-12-13 07:28:12

问题


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);
}

}

In same request, in initBinder() function eventValidator is NULL and in postAddEventForm() function eventValidator is holding the instance.

Please help on this.


回答1:


Access specifier of initBinder() method should be public -

public void initBinder(WebDataBinder binder) {


来源:https://stackoverflow.com/questions/41372252/spring-autowired-bean-giving-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!