问题:在自定义拦截器中,使用了@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

解决Spring Boot 拦截器注入service为空的问题的更多相关文章

  1. springboot拦截器注入service为空

    一般都是因为除了在拦截器之外,还需要在拦截器的配置类中,注册拦截器时没有使用spring的bean,而是使用了new创建bean造成的. @Configuration public class Web ...

  2. Spring boot拦截器的实现

    Spring boot拦截器的实现 Spring boot自带HandlerInterceptor,可通过继承它来实现拦截功能,其的功能跟过滤器类似,但是提供更精细的的控制能力. 1.注册拦截器 @C ...

  3. 【spring boot】spring boot 拦截器

    今日份代码: 1.定义拦截器 import com.alibaba.fastjson.JSON; import org.apache.commons.collections.CollectionUti ...

  4. spring boot拦截器配置

    1.在spring boot配置文件application.properties中添加要拦截的链接 com.url.interceptor=/user/test 2.编写拦截器代码 ,创建UrlInt ...

  5. (22)Spring Boot 拦截器HandlerInterceptor【从零开始学Spring Boot】

    上一篇对过滤器的定义做了说明,也比较简单.过滤器属于Servlet范畴的API,与Spring 没什么关系.     Web开发中,我们除了使用 Filter 来过滤请web求外,还可以使用Sprin ...

  6. spring boot拦截器中获取request post请求中的参数

    最近有一个需要从拦截器中获取post请求的参数的需求,这里记录一下处理过程中出现的问题. 首先想到的就是request.getParameter(String )方法,但是这个方法只能在get请求中取 ...

  7. spring boot拦截器WebMvcConfigurerAdapter,以及高版本的替换方案(转)

    文章转自 http://blog.51cto.com/12066352/2093750 最近项目采用spring icloud,用的spring boot版本是1.5.x的,spring boot 2 ...

  8. Spring boot 拦截器和过滤器

    1. 过滤器 Filter介绍 Filter可以认为是Servlet的一种“加强版”,是对Servlet的扩展(既可以对请求进行预处理,又可以对处理结果进行后续处理.使用Filter完整的一般流程是: ...

  9. spring boot拦截器WebMvcConfigurerAdapter,以及高版本的替换方案

    Springboot中静态资源和拦截器处理(踩了坑)   背景: 在项目中我使用了自定义的Filter 这时候过滤了很多路径,当然对静态资源我是直接放过去的,但是,还是出现了静态资源没办法访问到spr ...

随机推荐

  1. 《Linux》跟老男孩学Linux核心系统命令

    一.命令行简介 1.1 Linux 命令行提示符介绍 [root@root_pc ~]# #<==这是超级管理员root用户对应的命令行 [oldboy@oldboy_pc ~]$ #<= ...

  2. rabbitMq 学习笔记(二) 备份交换器,过期时间,死信队列,死信队列

    备份交换器 备份交换器,英文名称为 Altemate Exchange,简称庙,或者更直白地称之为"备胎交换器". 生产者在发送消息的时候如果不设置 mandatory 参数, 那 ...

  3. 【转载】C#使用Math.Ceiling方法对计算结果向上取整操作

    在C#的数值运算中,有时候需要对计算结果进行向上取整操作,支持设定结算结果的有效位数,Math.Ceiling方法是C#中专门用来对数值进行向上取整的方法,此方法和Math.Round方法.Math. ...

  4. Oracle 子查询(复杂select语句)

    在执行数据操作时,如果某个操作需要依赖于另外一个 select语句的查询结果,那么就可以把 select 语句迁入到该操作语句中,这样就形成了一个子查询.实际应用中,表与表之间相互关联,相互依存,这样 ...

  5. UCOSIII钩子函数

    OSIdleTaskHook 空闲任务调用这个函数,可以用来让CPU进入低功耗模式 void OSIdleTaskHook (void) { #if OS_CFG_APP_HOOKS_EN > ...

  6. sqlserver数据库的启动

    sqlserver实例几种启动的方法: (1)在WINDOWS服务控制台里手动启动,或者自动启动(默认) 第二种方式是SQLSERVER本身自已提供的启动方式,可以手动启动 (3)在SQLSERVER ...

  7. 4.kafka API producer

    1.Producer流程首先构建待发送的消息对象ProducerRecord,然后调用KafkaProducer.send方法进行发送.KafkaProducer接收到消息后首先对其进行序列化,然后结 ...

  8. Docker -compose install Harbor

    Docker-compose Harbor install Docker install Yum install docker-compose 首先安装 yum configuation 管理工具 [ ...

  9. python面试总结3(性能分析优化,GIl常考题)

    python性能分析和优化,GIL常考题 什么是Cpython GIL Cpython解释器的内存管理并不是线程安全的 保护多线程情况下对python对象访问 Cpython使用简单的锁机制避免多个线 ...

  10. SpringCloud学习心得—1.3—Eureka与REST API

      SpringCloud学习心得—1.3—Eureka与REST API Eureka的REST API接口 API的基本访问 Eureka REST APIEureka 作为注册中心,其本质是存储 ...