0

I have an interceptor on spring that intercepts requisitions of the user. I want to calculate the duration of the requisition and save to the database. However spring wont autowire my bean, causing a NullPointerException on service.save(log);

Here's the code:

import java.time.Duration;
import java.time.ZonedDateTime;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
 
/**
 *
 * @author Shadows
 */
@Component
public class Interceptador implements HandlerInterceptor {
 
    @Autowired
    LogService service;
 
    public Interceptador() {
    }
 
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
 
        //Create the log
        Log log = new Log();
 
        //Catch the URI the user is trying to access
        log.setPath(request.getRequestURI());
 
        //Set the log to request attr
        request.setAttribute("log", log);
 
        //
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }
 
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
 
        //Retrieve the log
        Log log = (Log) request.getAttribute("log");
 
        //Calculate the time of the requisition
        log.setDuracao(Duration.between(log.getDataCriacao(), ZonedDateTime.now()));
 
        //java.lang.NullPointerException:
        service.save(log);
        
        System.out.println(log.getDuracao());
 
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }

How can I avoid this NPE ?

KenobiBastila
  • 539
  • 4
  • 16
  • 52
  • let me guess you are registering it like this `interceptorRegistry.addInterceptor(new Interceptador());`. See the question marked as duplicate. – M. Deinum Sep 29 '22 at 06:48

1 Answers1

0

You need to registry your interseptor.

This is the same issue question with an answer: Cannot Autowire Service in HandlerInterceptorAdapter

And this is link to baeldung example: https://www.baeldung.com/spring-mvc-handlerinterceptor