首页 > 技术文章 > 【SpingBoot】spring静态工具类注入问题

zwqh 2018-10-16 10:07 原文

package cn.zwqh.action;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Component;

import cn.hkwl.basedata.common.CookieUtil;
import cn.hkwl.basedata.common.constant.ICookieConstants;
import cn.hkwl.basedata.common.constant.ISessionContants;
import cn.hkwl.basedata.common.redis.RedisHandle;
import cn.hkwl.basedata.session.SessionUser;

/**
 * 说明 :Session操作帮助类
 * 
 * @author 朝雾轻寒
 * @version 2018-09-26 09:30
 */

@Component
public class SessionUtils {
    
    @Resource  //(或者@Autowired)
    private RedisHandle redisHandle;

    private static SessionUtils sessionUtils;
    
    @PostConstruct
    public void init() {
        sessionUtils = this;
    }

    /**
     * 
     * 说明 :使用默认request获取登录的用户信息
     * 
     * @throws Exception
     */
    public static SessionUser getLoginUser() throws Exception {
        return (SessionUser) sessionUtils.redisHandle
                .get(CookieUtil.getValue(ServletActionContext.getRequest(), ICookieConstants.LOGIN_USER_KEY));
    }
}

还有点要注意:sessionUtils如果报空指针,需要检查下当前包名是否被@ComponentScan 扫描到,一开始是总以为是注入有问题,原谅我第一次整合springboot。。。

推荐阅读