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

    }

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM