Springboot自定义工具类中调用mapper或者service接口方式

1、该类使用@Component注解

2、添加一个本类类型的静态字段

3、创建一个初始化方法,贴上@PostConstruct 标签,用于注入bean

4、创建方法调用mapper或service接口

5、最后直接在普通类中调用即可

@Component
public class TokenUtil {

    @Autowired
    private  RedisTemplate redisTemplate;

    private static TokenUtil tokenUtil;

    @PostConstruct
    public void init() {
        tokenUtil = this;
        tokenUtil.redisTemplate = this.redisTemplate;
    }

    public static User getUser(HttpServletRequest request){
        String userName = getUserName(request);
        String key = Constant.USER + userName;
        User redisUser = (User) tokenUtil.redisTemplate.opsForValue().get(key);
        return redisUser;
    }

    private static String getUserName(HttpServletRequest request){
        String token = request.getHeader("Authorization");
        return JwtUtils.getuserName(token);
    }
}
posted @ 2022-09-29 14:19  leepandar  阅读(748)  评论(0编辑  收藏  举报