解决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
解决Spring Boot 拦截器注入service为空的问题的更多相关文章
- springboot拦截器注入service为空
一般都是因为除了在拦截器之外,还需要在拦截器的配置类中,注册拦截器时没有使用spring的bean,而是使用了new创建bean造成的. @Configuration public class Web ...
- Spring boot拦截器的实现
Spring boot拦截器的实现 Spring boot自带HandlerInterceptor,可通过继承它来实现拦截功能,其的功能跟过滤器类似,但是提供更精细的的控制能力. 1.注册拦截器 @C ...
- 【spring boot】spring boot 拦截器
今日份代码: 1.定义拦截器 import com.alibaba.fastjson.JSON; import org.apache.commons.collections.CollectionUti ...
- spring boot拦截器配置
1.在spring boot配置文件application.properties中添加要拦截的链接 com.url.interceptor=/user/test 2.编写拦截器代码 ,创建UrlInt ...
- (22)Spring Boot 拦截器HandlerInterceptor【从零开始学Spring Boot】
上一篇对过滤器的定义做了说明,也比较简单.过滤器属于Servlet范畴的API,与Spring 没什么关系. Web开发中,我们除了使用 Filter 来过滤请web求外,还可以使用Sprin ...
- spring boot拦截器中获取request post请求中的参数
最近有一个需要从拦截器中获取post请求的参数的需求,这里记录一下处理过程中出现的问题. 首先想到的就是request.getParameter(String )方法,但是这个方法只能在get请求中取 ...
- spring boot拦截器WebMvcConfigurerAdapter,以及高版本的替换方案(转)
文章转自 http://blog.51cto.com/12066352/2093750 最近项目采用spring icloud,用的spring boot版本是1.5.x的,spring boot 2 ...
- Spring boot 拦截器和过滤器
1. 过滤器 Filter介绍 Filter可以认为是Servlet的一种“加强版”,是对Servlet的扩展(既可以对请求进行预处理,又可以对处理结果进行后续处理.使用Filter完整的一般流程是: ...
- spring boot拦截器WebMvcConfigurerAdapter,以及高版本的替换方案
Springboot中静态资源和拦截器处理(踩了坑) 背景: 在项目中我使用了自定义的Filter 这时候过滤了很多路径,当然对静态资源我是直接放过去的,但是,还是出现了静态资源没办法访问到spr ...
随机推荐
- 传统IDC 部署网站
选择IDC机房 1.选择云主机. 2.传统IDC a购买服务器 b服务器托管 c装系统 装系统 虚拟机软件 vmware workstation virtualbox hyper-v 下载:r.ami ...
- Java调用Http/Https接口(1)--编写服务端
Http接口输入的数据一般是键值对或json数据,返回的一般是json数据.本系列文章主要介绍Java调用Http接口的各种方法,本文主要介绍服务端的编写,方便后续文章里的客户端的调用.文中所使用到的 ...
- vue.js相关教程
Vue.js——60分钟快速入门 http://www.cnblogs.com/keepfool/p/5619070.html
- FreeRTOS任务运行时间信息统计
相关宏的设置 configGENERATE_RUN_TIME_STATS //使能 portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() //配置一个高精度定时器/计数器提 ...
- zabbix-web界面显示中文
转载:https://www.cnblogs.com/miclesvic/p/6145171.html 1.确认zabbix是否开启了中文支持功能(/var/www/html/zabbix/inclu ...
- 个性化排序算法实践(三)——deepFM算法
FM通过对于每一位特征的隐变量内积来提取特征组合,最后的结果也不错,虽然理论上FM可以对高阶特征组合进行建模,但实际上因为计算复杂度原因,一般都只用到了二阶特征组合.对于高阶特征组合来说,我们很自然想 ...
- linux系统编程之信号(七)
今天继续学习信号,主要是学习关于时间和定时器相关的函数的使用,关于这个实际上有很多内容,这里先简要进行说明,等之后再慢慢进行相关深入,也主要是为接下来要做的一个综合linux系统编程的例子做准备,好了 ...
- 小程序~获取手机号getPhoneNumber提示该appid没有权限
处理思路 (1)小程序是不是企业主体 (2)有没有进行认证 (3)如果没有 是不可以获取用户手机号码的 .
- 【OI备忘录】trick汇总帖
OI中的那些实用的小trick 在OI中,我们时常会用到一些小技巧,无论是代码方面还是数学方面抑或是卡常,都有很多不错的小技巧. 鄙人不才,往往没办法想出来,于是就有了这篇汇总帖~ 如有疏漏,还请da ...
- Enterprise Architect 14破解版 安装包 安装教程
安装包以及破解补丁下载: 链接:https://pan.baidu.com/s/1es0wN_6-d9pk4xnSN1SiFA 提取码:bor0 安装包链接失效可在下方留言 安装以及破解教程 参考链接 ...