【问题标题】:Spring @Autowired bean giving nullSpring @Autowired bean 给 null
【发布时间】: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


【解决方案1】:

initBinder() 方法的访问说明符应该是public -

public void initBinder(WebDataBinder binder) {

【讨论】:

  • 谢谢维卡斯。您能否提供一个简短的信息,这就是我们需要公开的原因。
猜你喜欢
  • 2018-07-19
  • 1970-01-01
  • 2018-06-15
  • 1970-01-01
  • 1970-01-01
  • 2014-12-15
  • 2015-08-07
  • 2019-08-11
  • 1970-01-01
相关资源
最近更新 更多