解决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 ...
随机推荐
- 前端开发 vue,angular,react框架对比2
在过去一年里,前端开发发展迅速,前端工程师的薪资亦是水涨船高.2019 更是热度不减,而作为近年来尤为热门的前端框架,Vue.js 自是积累了大量关注.那么,Vue.js 是适合你的框架吗? ...
- 5_PHP数组_3_数组处理函数及其应用_6_数组检索函数
以下为学习孔祥盛主编的<PHP编程基础与实例教程>(第二版)所做的笔记. 数组检索函数 1. array_keys() 函数 程序: <?php $interests[2] = &q ...
- 2.将多个元素设置为同一行?清除浮动有几种方式?【HTML】
1.将多个元素设置为同一行:float,inline-block 清除浮动的方式: 方法一:添加新的元素 .应用 clear:both: 方法二:父级div定义 overflow: hidden: 方 ...
- Oracle - 实现MySQL的limit功能
MySQL的limit功能是获取指定行数的数据,Oracle没有这个limit,但是有其它方法. oracle数据库不支持mysql中limit功能,但可以通过rownum来限制返回的结果集的行数,r ...
- Fortify漏洞之 Privacy Violation(隐私泄露)和 Null Dereference(空指针异常)
继续对Fortify的漏洞进行总结,本篇主要针对 Privacy Violation(隐私泄露) 和 Null Dereference(空指针异常) 的漏洞进行总结,如下: 1.1.产生原因: Pri ...
- c# zip写comment注释
//生成的压缩文件为test.zip using (FileStream fsOut = File.Create("test.zip")) { //ZipOutputStream类 ...
- 如何在SAP Cloud Platform ABAP编程环境里创建一个employee
用ABAP Development Tool登录SAP Cloud Platform ABAP编程环境后,对ABAP项目点击右键,选择属性,从而找到该环境的web访问的url: https://325 ...
- django图片上传修改图片名称
storage.py # 给上传的图片重命名 from django.core.files.storage import FileSystemStorage from django.http impo ...
- MySQL FEDERATED引擎使用示例, 类似Oracle DBLINK(转)
1 引擎说明 本地MySQL数据库要访问远程MySQL数据库的表中的数据, 必须通过FEDERATED存储引擎来实现. 有点类似Oracle中的 数据库链接(DBLINK). 要允许这个存储引擎, 当 ...
- 【hadoop】在eclipse上运行WordCount的操作过程
序:本以为今天花点时间将WordCount例子完全理解到,但高估自己了,更别说我只是在大学选修一学期的java,之后再也没碰过java语言了 总的来说,从宏观上能理解具体的程序思路,但具体到每个代码有 ...