Asrar Mavli
Asrar Mavli

Reputation: 53

Spring @Autowired bean giving null

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.

Upvotes: 0

Views: 360

Answers (1)

Vikas Sachdeva
Vikas Sachdeva

Reputation: 5803

Access specifier of initBinder() method should be public -

public void initBinder(WebDataBinder binder) {

Upvotes: 2

Related Questions