解决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 ...
随机推荐
- spark源码阅读--SparkContext启动过程
##SparkContext启动过程 基于spark 2.1.0 scala 2.11.8 spark源码的体系结构实在是很庞大,从使用spark-submit脚本提交任务,到向yarn申请容器,启 ...
- MySql 严格模式相关配置
目录 MySql 严格模式 MySQL的sql_mode合理设置 sql model 常用来解决下面几类问题 sql_mode常用值 注意 改为严格模式后可能会存在的问题 模式设置和修改(以解决上述问 ...
- Fortify漏洞之Denial of Service: Regular Expression
继续对Fortify的漏洞进行总结,本篇主要针对 Denial of Service: Regular Expression 漏洞进行总结,如下: 1.Denial of Service: Reg ...
- EhLib使用全攻略
使用 TDBSumList 组件 还记得以前有朋友问过这样一个问题:在 DBGrid 下如何像 Excel 一样能够做统计计算,实话说,使用 DBGrid 来做的话着实不易,不过现在有了这个咚咚, ...
- Cephfs 部署 创建 metadata 池 data池
上一次部署了ceph分布式存储,接下来我们部署ceph的文件系统.Ceph文件系统至少需要两个RADOS池,一个用于数据,一个用于元数据. 创建metadata 池 后面数字表示 PG 和pgp数 c ...
- C++(四十二) — 函数模板多态
1.函数模板(参数多态) 相当于一个函数发生器,参数多态,可以重载. 普通函数和模板函数的本质区别: 普通函数的调用,可以进行隐式的类型转换: 函数模板的调用,使用类型参数化,严格按照类型进行匹配, ...
- S3cmd
一:安装方法 #wget http://nchc.dl.sourceforge.net/project/s3tools/s3cmd/1.0.0/s3cmd-1.0.0.tar.gz #tar -zxf ...
- Problem E: 数量的类模板
#include<iostream> #include<iomanip> #include<algorithm> using namespace std; temp ...
- 《少年先疯队》第八次团队作业:Alpha冲刺第一天
前言 第一天冲刺会议 时间:2019.6.14 地点:9C406 1.1 今日完成任务情况以及遇到的问题. 1.1.1今日完成任务情况 姚玉婷:管理员登录功能的实现,用户登录功能的实现 ...
- machine learning (4)---feature scaling
feature scaling:缩小或扩大feature的值,使所有的feature处于类似的范围,这样进行gradient descnet时更快趋向最小值.因为不同的feature的范围相差很大时, ...