工具类注入需要的service或配置类--亲测可行

 代码如下(注解的方式,推荐使用这种):

@Component //关键一:添加此注解才能被spring扫描到
public class TokenUtils {
    private static final Integer REDIS_TIME = 60 * 60 * 24 * 365;
    private static final Integer CODE_TIME = 60 * 60;
    private static final ObjectMapper MAPPER = new ObjectMapper();
 
    
    @Autowired
    private  RedisService rService; //关键二:添加需要的服务类
    public static TokenUtils tokenUtils; //关键三:声明一个当前类的静态对象
 
    @PostConstruct  //关键四:通过@PostConstruct注解实现注入
    public void init() {
        tokenUtils = this;
        //tokenUtils.rService =  this.rService;
    }
 
 
    /**
     * 查找此token对应的值
     *
     * @param token
     * @return
     */
    public static String getDataByKey(String token) {
        String key = "TOKEN_" + token;
        return tokenUtils.rService.get(key);
    }
}
 

猜你喜欢

转载自blog.csdn.net/YINZONGCHAO/article/details/107311055