How can i reduce repetitive code in spring boot controllers

j.sinjaradze :

I've just started to use spring boot for my services. I have few controllers that use same code in their bodies. for example in every controller I have to check if request object obtained from request is null or not:

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

I know that repeating code in several controllers is not a good approach, so I was wondering if there is a way to prevent code repetition, or if spring boot has a solution for the mentioned problem.

BSeitkazin :

You are using SpringBoot, so in your application, where you define @SpringBootApplication annotation, you can specify the next @Bean:

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

Also create MyHttpRequestHandler class, where you can make any your logic with that:

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");
        }
   }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=90739&siteId=1