Spring MVC 无法在拦截器上使用服务[duplicate]

kx7yvsdv  于 2022-11-14  发布在  Spring
关注(0)|答案(1)|浏览(156)

此问题在此处已有答案

Why is my Spring @Autowired field null?(21个答案)
上个月关门了。
我在spring上有一个拦截器,拦截用户的请求。我想计算请求的持续时间并保存到数据库中。但是spring不会自动连接我的bean,导致在www.example.com上出现NullPointerExceptionservice.save(log);
代码如下:

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

如何避免此NPE?

huwehgph

huwehgph1#

你需要注册你的interseptor。
这是同一个问题的问题与答案:Cannot Autowire Service in HandlerInterceptorAdapter
而这是链接到baeldung的例子:https://www.baeldung.com/spring-mvc-handlerinterceptor

相关问题