springboot拦截中自动注入的组件为null问题解决方法
一、写SpringUtil类来获取Springh管理的类实例,判断是否注入成功,如果没有注入成功重新获取注入
package com.util; import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component; @Component
public class SpringUtil implements ApplicationContextAware
{ private static ApplicationContext applicationContext; @Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException
{
if (SpringUtil.applicationContext == null)
{
SpringUtil.applicationContext = applicationContext;
} //"ApplicationContext配置成功,在普通类可以通过调用SpringUtils.getAppContext()获取applicationContext对象,applicationContext="
} // 获取applicationContext
public static ApplicationContext getApplicationContext()
{
return applicationContext;
} // 通过name获取 Bean.
public static Object getBean(String name)
{
return getApplicationContext().getBean(name);
} // 通过class获取Bean.
public static <T> T getBean(Class<T> clazz)
{
return getApplicationContext().getBean(clazz);
} // 通过name,以及Clazz返回指定的Bean
public static <T> T getBean(String name, Class<T> clazz)
{
return getApplicationContext().getBean(name, clazz);
} }
二、在拦截器中若自动注入没有生效,需要手动判断后,重新赋值
package com.webconfig; import java.util.Date; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView; import com.entity.TokenEntity;
import com.repository.TokenRepository;
import com.util.CommonUtil; import sun.misc.BASE64Decoder; @Component
public class TokenInterceptor implements HandlerInterceptor
{ private final static BASE64Decoder decode = new BASE64Decoder();
@Autowired
private TokenRepository tokenRep; // 在请求处理之前进行调用(Controller方法调用之前
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
{
String token = request.getParameter("token");
String msg = "";
boolean canFilter = false;
if (!CommonUtil.isNull(token))
{
String tokenStr = new String(decode.decodeBuffer(token));
String[] tokens = tokenStr.split("_");
if (tokens.length == 2)
{
if (tokenRep == null)
{
// 解决tokenRep为null无法注入问题
//System.out.println("TokenRepository is null!!!");
BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
tokenRep = (TokenRepository) factory.getBean("tokenRepository");
}
String userName = tokens[0];
String curToken = tokens[1];
TokenEntity tokenInfo = tokenRep.findByUserName(userName);
if (tokenInfo != null)
{
if (curToken.equals(tokenInfo.getToken()))
{
tokenInfo.setCreatTime(new Date());
tokenRep.save(tokenInfo);
canFilter = true;
} else
{
msg = "The user is logged in elsewhere and token has failed";
}
} else
{
msg = "Token has expired,please get it again";
}
} else
{
msg = "token fomart incorrect";
} } else
{
msg = "token is empty";
} if (canFilter)
{
return true;
} else
{
response.setCharacterEncoding("UTF-8");
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.getWriter().println(msg);
}
return false;
} // 请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后)
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception
{
// TODO Auto-generated method stub } // 在整个请求结束之后被调用,也就是在DispatcherServlet 渲染了对应的视图之后执行(主要是用于进行资源清理工作)
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception
{
// TODO Auto-generated method stub } }
springboot拦截中自动注入的组件为null问题解决方法的更多相关文章
- 关于springboot项目中自动注入,但是用的时候值为空的BUG
最近想做一些web项目来填充下业余时间,首先想到了使用springboot框架,毕竟方便 快捷 首先:去这里 http://start.spring.io/ 直接构建了一个springboot初始化的 ...
- 带你开发一款给Apk中自动注入代码工具icodetools(完善篇)【申明:来源于网络】
带你开发一款给Apk中自动注入代码工具icodetools(完善篇)[申明:来源于网络] 带你开发一款给Apk中自动注入代码工具icodetools(完善篇):http://blog.csdn.net ...
- SpringBoot JPA 中无法注入 JpaRepository 接口的问题及解决方案
错误: 在Springboot 框架中使用JPA的过程中,怎么来实现数据库操作底层的交互呢?Spring JPA其实已经提供了一套很全面的解决方案,实现对数据库的增.删.查.改只需要继承JPA实现类 ...
- SpringBoot+MyBatis中自动根据@Table注解和@Column注解生成增删改查逻辑
习惯使用jpa操作对象的方式,现在用mybatis有点不习惯. 其实是懒得写SQL,增删改查那么简单的事情你帮我做了呗,mybatis:NO. 没办法,自己搞喽! 这里主要是实现了通过代码自动生成my ...
- SpringBoot+MyBatis中自动根据@Table注解和@Column注解生成ResultMap
其实我一点都不想用mybatis,好多地方得自己写,比如这里. 使用mybatis要写大量的xml,烦的一批.最烦人的莫过于写各种resultmap,就是数据库字段和实体属性做映射.我认为这里应该是m ...
- Springboot 拦截器 依赖注入失败
解决方案2种. ====1 https://blog.csdn.net/shunhua19881987/article/details/78084679 ====2 https://www.cnblo ...
- System.Runtime.InteropServices.COMException 检索COM类工厂中CLSID{xxxxxxxxx}的组件时失败解决方法
iis7.5中设定应用程序池中<进程模型>中<标识>为localSystem 提示:System.Runtime.InteropServices.COMException: 命 ...
- Selenium中自动输入10位随机数字的方法
有时候项目中需要输入快递号,对于已输入过的快递单号则不能再次输入,这种问题怎么解决呢,可以看下这个方法 public static final String ALLCHAR = "01234 ...
- Idea中自动生成get,set,toString等方法
https://blog.csdn.net/sinat_41226396/article/details/80770520 自动生成main函数: https://blog.csdn.net/fanr ...
随机推荐
- linux IP 网关配置
1. 关闭selinux 与防火墙 在虚拟机装好之后之后,先关闭selinux与防火墙 关闭selinx,重启生效 vim /etc/selinux/config 修改 SELINUX=disable ...
- iOS真机调试之免费预配(Free provisioning)
免费预配允许开发者在不加入Applec Developer Program的情况下,可以发布和测试App 注意:免费预配(Free Provisioning)与自动预配(Auto Provisioni ...
- vxWorks下常用的几种延时方法
在应用编程的时候,通常会碰到需要一个任务在特定的延时之后执行一个指定的动作,如等待外设以确保数据可靠,控制扬声器发声时间以及串口通信超时重发等.这就需要利用定时器机制来计量特定长度的时间段. ...
- 技术选型之Docker容器引擎
https://mp.weixin.qq.com/s?__biz=Mzg3NjAyOTUzMQ==&mid=2247484524&idx=1&sn=ac041bf3e36dda ...
- 手机APP流量的发送与获取功能的实现
package com.loaderman.trafficdemo; import android.content.Context; import android.content.Intent; im ...
- C++异常实现机制
1.C函数的调用和返回 要理解C++异常机制实现之前,首先要了解一个函数的调用和返回机制,这里面就要涉及到ESP和EBP寄存器.我们先看一下函数调用和返回的流程. 下面是按调用约定__stdcall ...
- Service-stack.redis 使用PooledRedisClientManager 速度慢的原因之一
现在越来越多的开发者使用service-stack.redis 来进行redis的访问,但是获取redisclient的方式有多种方式,其中有一种从缓冲池获取client的方式很是得到大家的认可. L ...
- vue-router懒加载
require.ensure(dependencies:String [],callback:function(require),errorCallback:function(error),chunk ...
- 不容错过的 Babel7 知识
对 Babel 的配置项的作用不那么了解,是否会影响日常开发呢?老实说,大多情况下没有特别大的影响(毕竟有搜索引擎). 不过呢,还是想更进一步了解下,于是最近认真阅读了 Babel 的文档,外加不断编 ...
- 常见IE6兼容问题总结
1.<!DOCTYPE HTML>文档类型的声明. 产生条件:IE6浏览器,当我们没有书写这个文档声明的时候,会触发IE6浏览器的怪异解析现象: 解决办法:书写文档声明. 2.不同浏览器当 ...