代码之家  ›  专栏  ›  技术社区  ›  j.sinjaradze

如何减少spring引导控制器中的重复代码

  •  3
  • j.sinjaradze  · 技术社区  · 7 年前

    if (request == null){
        throw new InvalidRequestException("the request object is null");
    }
    

    我知道在多个控制器中重复代码不是一个好方法,所以我想知道是否有一种方法可以防止代码重复,或者spring boot是否有解决上述问题的方法。

    8 回复  |  直到 7 年前
        1
  •  4
  •   BSeitkazin    7 年前

    您使用的是SpringBoot,因此在您的应用程序中 @SpringBootApplication @Bean :

    @Bean
    public HttpRequestHandler httpRequestHandler () {
        return new MyHttpRequestHandler();
    }
    

    同时创建 MyHttpRequestHandler

    public class MyHttpRequestHandler implements HttpRequestHandler {
    
    @Override
    public void handleRequest (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            if (request == null) {
                throw new InvalidRequestException("the request object is null");
            }
       }
    }
    
        2
  •  1
  •   Niraj Sonawane    7 年前

    基本上你要做的就是参数验证。这是一种横切关注点,是使用AOP方法的完美用例。

    春天提供了一个很好的方法

    你可以简单地使用 @validate

    @PostMapping
        public ResponseEntity<Void> someMEthod(@Validated(CustomChecks.class) @RequestBody request yourRequest)
    

    然后可以将所有验证逻辑放在CustomChecks类中(你可以找到一些例子)

    如果有非常小的通用验证,那么也可以使用注释。

    @不为空 请求类的注释。看看这个 example

    希望这有帮助

        3
  •  0
  •   Lorelorelore R. Foxwood    7 年前

    protected void checkRequest(Object request){
        if (request == null){
            throw new InvalidRequestException("the request object is null");
        }
    }
    

    并以书面形式声明 AbstractController 班级。让您的控制器扩展这个类。

        4
  •  0
  •   Paris Karagiannopoulos    7 年前

        5
  •  0
  •   Fima Taf    7 年前

    一种方法是创建一个抽象类,该类将包含一个将由扩展控制器调用的包装方法。

    public abstract class CoreController {
      protected void validateRequest(MyRequest request) {
        if (request == null) throw new InvalidRequestException("the request object is null");
      }
    }
    

    validateRequest

    public class MyController extends CoreController {
      @PostMapping("/some_endpoint")
      public MyResponse endpointMethod (@RequestBody MyRequest request) {
        validateRequest(request);
        ...
        return new MyResponse();
      }
    }
    
        6
  •  0
  •   Z fp    7 年前

    春季AOP?

    @Aspect
    class AopDemo{
    
        @Around("execution(* com.demo.controller.*(..))")
        public Object release(JoinPoint jp){
            try{
                Object[] args = jp.getArgs();
                for(Object arg: args){
                    if(arg == null){
                        throw new InvalidRequestException("the request object is null"); 
                    }
                }
                return jp.proceed(args);
            }catch(InvalidRequestException ire){
                // handle InvalidRequestException
            }catch(Exception ex){
                // handle Exception
            }
        }
    
    }
    
        7
  •  0
  •   Raj    7 年前

    我同意@Niraj Sonawane使用@Validated注释来处理帖子中给出的具体案例。

    除此之外,使用过滤器可能是处理属于“执行控制器操作的先决条件”的情况的另一种选择。我们使用一个复杂的逻辑来解析访问权限,这是我们在设计中拥有的所有控制器所需要的。我们用过滤器来处理。

        8
  •  0
  •   darshakat    7 年前

    更好地使用 @有效 检查有效载荷,无需手动检查。请按照下面的解释。

    导入org.springframework.validation.Errors; @有效 如下所示。

    @PostMapping("/test")
    public ResponseEntity<String> editStatus(@Valid @RequestBody Person person, Errors errors) {
        String responseMessage;
        if(errors.hasErrors()) {
            responseMessage = "'" + errors.getFieldError().getField() + "' " + errors.getFieldError().getDefaultMessage();
        } else {
            // You can do ur logic here
            responseMessage = "result";
        }
        return ResponseEntity.accepted().body(responseMessage);
    }
    

    您可以如下验证的人员有效负载。

    public class Person {
        @NotNull
        private String firstName;
        @NotNull
        private String lastName;
        private String city;
    
        //Getter
        //Setter
    }
    

    @有效 错误 .