一、写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问题解决方法的更多相关文章

  1. 关于springboot项目中自动注入,但是用的时候值为空的BUG

    最近想做一些web项目来填充下业余时间,首先想到了使用springboot框架,毕竟方便 快捷 首先:去这里 http://start.spring.io/ 直接构建了一个springboot初始化的 ...

  2. 带你开发一款给Apk中自动注入代码工具icodetools(完善篇)【申明:来源于网络】

    带你开发一款给Apk中自动注入代码工具icodetools(完善篇)[申明:来源于网络] 带你开发一款给Apk中自动注入代码工具icodetools(完善篇):http://blog.csdn.net ...

  3. SpringBoot JPA 中无法注入 JpaRepository 接口的问题及解决方案

    错误: 在Springboot  框架中使用JPA的过程中,怎么来实现数据库操作底层的交互呢?Spring JPA其实已经提供了一套很全面的解决方案,实现对数据库的增.删.查.改只需要继承JPA实现类 ...

  4. SpringBoot+MyBatis中自动根据@Table注解和@Column注解生成增删改查逻辑

    习惯使用jpa操作对象的方式,现在用mybatis有点不习惯. 其实是懒得写SQL,增删改查那么简单的事情你帮我做了呗,mybatis:NO. 没办法,自己搞喽! 这里主要是实现了通过代码自动生成my ...

  5. SpringBoot+MyBatis中自动根据@Table注解和@Column注解生成ResultMap

    其实我一点都不想用mybatis,好多地方得自己写,比如这里. 使用mybatis要写大量的xml,烦的一批.最烦人的莫过于写各种resultmap,就是数据库字段和实体属性做映射.我认为这里应该是m ...

  6. Springboot 拦截器 依赖注入失败

    解决方案2种. ====1 https://blog.csdn.net/shunhua19881987/article/details/78084679 ====2 https://www.cnblo ...

  7. System.Runtime.InteropServices.COMException 检索COM类工厂中CLSID{xxxxxxxxx}的组件时失败解决方法

    iis7.5中设定应用程序池中<进程模型>中<标识>为localSystem 提示:System.Runtime.InteropServices.COMException: 命 ...

  8. Selenium中自动输入10位随机数字的方法

    有时候项目中需要输入快递号,对于已输入过的快递单号则不能再次输入,这种问题怎么解决呢,可以看下这个方法 public static final String ALLCHAR = "01234 ...

  9. Idea中自动生成get,set,toString等方法

    https://blog.csdn.net/sinat_41226396/article/details/80770520 自动生成main函数: https://blog.csdn.net/fanr ...

随机推荐

  1. Mac下搭建Vue开发环境

    认知: 注:上面的图片转自Vue2.0 新手入门 — 从环境搭建到发布 1.安装brew 打开终端运行以下命令: /usr/bin/ruby -e "$(curl -fsSL https:/ ...

  2. SQL编写自定义函数

    -- 通过一个子级ID 返回一级分类名称alter function calcclass(@dclassid as int)returns varchar(50)asbegin-- 通过一个子级ID ...

  3. vue 登录路由判断

    router.beforeEach((to, from, next) => { // alert(sessionStorage.getItem('accessToken')) // consol ...

  4. openerp学习笔记 视图中字段只变化(on_change)联动其他字段值、选择和过滤

    1.修改产品数量时,自动计算产品销售金额.销售成本和销售利润<field name="num" on_change="on_change_product(produ ...

  5. 常用的CSS样式示例代码

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  6. 自定义圆形图片控件CircleImageView的实现

    package com.loaderman.circleimageviewdemo; import android.content.Context; import android.content.re ...

  7. EPOLL内核原理极简图文解读(转)

    预备知识:内核poll钩子原理内核函数poll_wait把当前进程加入到驱动里自定义的等待队列上 当驱动事件就绪后,就可以在驱动里自定义的等待队列上唤醒调用poll的进程 故poll_wait作用:可 ...

  8. Git代码行数统计命令

    统计zhangsan在某个时间段内的git新增删除代码行数 git log --author=zhangsan--since=2018-01-01 --until=2019-04-01 --forma ...

  9. 阿里巴巴 fastjson-1.2.12.jar json解析异常java.lang.ClassFormatError: Invalid method Code length 66865 in class file com/alibaba/fastjson/serializer/ASMSerializer_6_UserKdlb

    承接上篇:fastjson反序列化LocalDateTime失败的问题java.time.format.DateTimeParseException: Text '2019-05-24 13:52:1 ...

  10. FSCalendar使用和注意事项

    相信大家项目中或多或少都有日历这一块的内容吧,公司作为教育行业的软件公司,当然也是一定有的. 最近被日历这一块的内容弄得很头疼啊,改来改去的,不过还是学到了很多东西,至少FSCalendar的使用基本 ...