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

    }

}

 

posted @ 2018-06-06 11:14  zincredible  阅读(2535)  评论(0编辑  收藏  举报