“需要一个豆子,但发现了2个” - 春天

时间:2017-07-18 09:03:57

标签: java spring javabeans

这是我的班级:

println(array[0]) // Outputs 1  
println(list[0]) // Outputs 1 

在我的项目中,我正在使用基于spring-boot / hibernate / java的配置并尝试实现异常处理机制。我正在使用我从StackOverflow获得的示例代码,并了解处理异常的最佳方法是什么弹簧。 但是当我运行代码时,我得到了这个错误。但是当我停止使用“ MessageSourceAccessor ”时,错误消失了。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import com.mportal.ec.exception.ApplicationSpecificException;

@ControllerAdvice
public class DefaultExceptionHandler extends ResponseEntityExceptionHandler {

    @Autowired
    private final MessageSourceAccessor messageSource;


    public DefaultExceptionHandler(MessageSourceAccessor messageSource) {
        Assert.notNull(messageSource, "messageSource must not be null");
        this.messageSource = messageSource;
     }

      //expected Exceptions
      @ExceptionHandler(ApplicationSpecificException.class)
      protected ResponseEntity<Object> handleApplicationSpecificException(final RuntimeException ex, final WebRequest request) {
          final String bodyOfResponse = "This should be application specific";
          return handleExceptionInternal(ex, bodyOfResponse, new HttpHeaders(), HttpStatus.NOT_FOUND, request);
      }


      //unexpected Exceptions
      @ExceptionHandler(Exception.class)
        protected ResponseEntity<Object> handleException(final RuntimeException ex, final WebRequest request) {
          final String bodyOfResponse = "This should be application specific";
          return handleExceptionInternal(ex, bodyOfResponse, new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR, request);
      }
}

如何解决此问题?

1 个答案:

答案 0 :(得分:4)

您正在使用构造函数注入和字段注入。

public DefaultExceptionHandler(MessageSourceAccessor messageSource) {
    Assert.notNull(messageSource, "messageSource must not be null");
    this.messageSource = messageSource;
 }

   @Autowired
   private final MessageSourceAccessor messageSource;

只选择一个。