解决Spring Boot 拦截器注入service为空的问题

问题:在自定义拦截器中,使用了@Autowaire注解注入了封装JPA方法的Service,结果发现无法注入,注入的service为空

0.原因分析

拦截器加载的时间点在springcontext之前,所以在拦截器中注入自然为null

1.需要在拦截器上加@Component

package com.fdzang.mblog.interceptor;

import com.fdzang.mblog.pojo.*;
import com.fdzang.mblog.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Optional;


@Component
public class InitInterceptor implements HandlerInterceptor { @Autowired OptionsService optionsService; @Autowired UserService userService; @Autowired PageService pageService; @Autowired LabelService labelService; @Autowired ArticleService articleService; @Autowired CategoryService categoryService; @Autowired TagService tagService; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception { // TODO Auto-generated method stub //controller方法调用之前 return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView mv) throws Exception { // TODO Auto-generated method stub //请求处理之后进行调用,但是在视图被渲染之前,即Controller方法调用之后 HttpServletRequest req = (HttpServletRequest) request; HttpSession session=req.getSession(); String isInited=(String)req.getSession().getAttribute("isInited"); Optional<String> isInited_op=Optional.ofNullable(isInited); if(!isInited_op.isPresent()) { List<Options> options = optionsService.findAll(); List<Page> pageNavigations = pageService.findAll(); List<Label> labels = labelService.findAll(); List<Category> mostUsedCategories = categoryService.getMostUsedCategories(); List<Tag> mostUsedTags = tagService.getMostUsedTags(); List<Article> mostCommentArticles = articleService.getMostCommentArticles(); List<Article> mostViewCountArticles = articleService.getMostViewCountArticles(); User adminUser = null; int paginationPageCount = 0; session.setAttribute("pageNavigations", pageNavigations); for (Options option : options) { session.setAttribute(option.getoId(), option.getOptionValue()); if (option.getoId().equals("adminEmail")) { adminUser = userService.getUserByEmail(option.getOptionValue()); session.setAttribute("adminUser", adminUser); System.out.println(adminUser.getUserName()); } } for (Label label : labels) { session.setAttribute(label.getoId(), label.getZh_cn()); } session.setAttribute("servePath", "localhost:8080"); session.setAttribute("isLoggedIn", false); session.setAttribute("loginURL", "/login"); session.setAttribute("mostUsedCategories", mostUsedCategories); session.setAttribute("mostUsedTags", mostUsedTags); session.setAttribute("paginationPageCount", paginationPageCount); session.setAttribute("mostCommentArticles", mostCommentArticles); session.setAttribute("mostViewCountArticles", mostViewCountArticles); session.setAttribute("isInited", "inited"); } } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) throws Exception { //在整个请求结束之后被调用,也就是在DispatcherServlet //渲染了对应的视图之后执行,主要是用于进行资源清理工作 } }

2.进行拦截器配置

package com.fdzang.mblog.config;

import com.fdzang.mblog.interceptor.InitInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class InterceptorConfig extends WebMvcConfigurerAdapter {
    @Bean
    public InitInterceptor myInterceptor(){
        return new InitInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //多个拦截器组成一个拦截器链
        // addPathPatterns用于添加拦截规则
        // excludePathPatterns用户排除拦截
        //对来自/** 全路径请求进行拦截
        registry.addInterceptor(myInterceptor()).addPathPatterns("/**");
        super.addInterceptors(registry);
    }
}

参考博客:https://blog.csdn.net/wmh13262227870/article/details/77005920

原文地址:https://www.cnblogs.com/fdzang/p/9556842.html