Java 在静态嵌套类上使用@ControllerAdvice是不是一种不好的实践

Java 在静态嵌套类上使用@ControllerAdvice是不是一种不好的实践

问题描述

在我的应用程序中,我需要使用两个不同的@ControllerAdvice注解类:其中一个处理特定的异常,另一个是处理所有意外异常的具有较低@Order的默认处理程序。然而,它们共享一些自定义逻辑用于从处理的异常构建ResponseEntity。

为了将代码放在一个地方并使共享的逻辑对它们可用,我想将这两个类作为静态嵌套类放入一个外部类中,像这样:

public class ExceptionHandler {

  private static ResponseEntity handleError(Exception ex, String message){ 
    // shared exception handling 
  }

  @ControllerAdvice
  @Order(Ordered.HIGHEST_PRECEDENCE)
  static class SpecializedExceptionHandler {

    @ExceptionHandler
    ResponseEntity handleMyException(MyException ex){
      return handleError(ex, "Custom Exception");
    }
  }

  @ControllerAdvice
  static class DefaultExceptionHandler {

    @ExceptionHandler
    ResponseEntity handleAllOtherExceptions(Exception ex){
      return handleError(ex, "Other Exception");
    }
  }
}

这似乎完美运作,我自己也想不出反对的理由,所以也许你可以帮帮我。

解决方案

一般的原则是,代码单元(Java 中的类)应该具有单一的目的。尽管这些实现在技术上是单一目的的,但它们通过存在于同一文件中而不必要地纠缠在一起。

最好是将它们拆分开,像这样:

public interface BaseExceptionHandler {

    default ResponseEntity handleError(Exception ex, String message) { 
        // shared exception handling 
    }
}

@ControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE)
public class SpecializedExceptionHandler implements BaseExceptionHandler {

    @ExceptionHandler
    ResponseEntity handleMyException(MyException ex){
        return handleError(ex, "Custom Exception");
    }
}

@ControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE)
public class DefaultExceptionHandler implements BaseExceptionHandler {

    @ExceptionHandler
    ResponseEntity handleAllOtherExceptions(Exception ex){
        return handleError(ex, "Other Exception");
    }
}

这也消除了使用static的方式,使其更加常规。

如果您更喜欢继承的风格:

public abstract class BaseExceptionHandler {

    ResponseEntity handleError(Exception ex, String message) { 
        // shared exception handling 
    }
}

public class SpecializedExceptionHandler extends BaseExceptionHandler {
   ...

如果你偏爱静态方法风格:

public final class ExceptionHandlerUtils {

    public static ResponseEntity handleError(Exception ex, String message) { 
        // shared exception handling 
    }
}

public class SpecializedExceptionHandler extends BaseExceptionHandler {
    // impl uses ExceptionHandlerUtils.handleError()

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程