解决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 ...
随机推荐
- cefsharp System.IO.FileNotFoundException: 未能加载文件或程序集“CefSharp.Core.dll”或它的某一个依赖项。
解决办法 安装vc++ 2015 Redistributable 64位系统安装x64 如果还报错先装x64版本再装x86版本 https://files.cnblogs.com/files/xuej ...
- 【OO学习】OO第三单元作业总结
[OO学习]OO第三单元作业总结 第三单元,我们学习了JML语言,用来进行形式化设计.本单元包括三次作业,通过给定的JML来实行了一个对路径的管理系统,最后完成了一个地铁系统,来管理不同的线路,求得关 ...
- Swift之xib模块化设计
一.解决问题 Xib/Storybarod可以方便.可视化的设置约束,在开发中也越来越重要.由于Xib不能组件化,使得封装.重用都变得不可行.本文将介绍一种解决方案,来实现Xib组件化. 二.模型块原 ...
- app后端设计(php)
来源:http://blog.csdn.net/column/details/mobilebackend.html?page=1 做了3年app相关的系统架构,api设计,先后在3个创业公司中工作,经 ...
- mysql如何让有数据的表的自增主键重新设置从1开始连续自增
项目开发中,有些固定数据在数据表中,主键是从1自增的,有时候我们会删除一些数据, 这种情况下,主键就会不连续.如何恢复到像第一次插入数据一样主键从1开始连续增长, 这里我找到一种解决方法: 如上面一张 ...
- SpringBoot AOP概念及使用Demo
AOP核心概念1.横切关注点 对哪些方法进行拦截,拦截后怎么处理,这些关注点称之为横切关注点2.切面(aspect)->(通知+切点) 类是对物体特征的抽象,切面就是对横切关注点的抽象.通知+切 ...
- windows+phpstudy(apache) 以cgi方式运行python
Apache配置 在httpd.conf中查找DocumentRoot: +ExecCGI 支持cgi DocumentRoot "F:\phpStud\PHPTutorial\WWW&qu ...
- IDEA中看Flink 1.9源码时报Sources not found for: org.apache.flink:flink-shaded-hadoop-2:2.4.1-7.0
1.场景 在阅读Flink 1.9源码时,个别类如YarnClientImpl.java只能查看.class文件,想查看对应的.java source文件,点击Download source时,报So ...
- 2. premiere 项目管理
1.premiere 项目管理 可以对项目素材进行一个管理,方便我们对项目文件的编辑 1.序列选择,管理前更改好名称 2.管理保留原始素材,不要选择转码 3.通过浏览,选择存储路径 点击“计算”,显示 ...
- Java精通并发-wait与sleep方法字节码分析
在上一次https://www.cnblogs.com/webor2006/p/11372521.html中对于Thread类和Runnable接口有了一个基本的认识,这次咱们继续巩固基础,首先先新建 ...