- 给当前的工具类加上@Component,使其成为一个bean对象
- 声明一个非静态的属性(加上注解@Autowired)和一个静态的属性。
- 声明一个返回值为void并且不能抛出异常的方法,在其中将非静态属性赋值给静态属性。该方法上加上注解@PostConstruct
- 这样就将service的值注入了进来。
@Component public class DemoUtil { @Autowired private RedisTemplate redisTemplate; private static RedisTemplate staticRedisTemplate; @PostConstruct public void init(){ staticRedisTemplate = redisTemplate; } public static void toolFun(){ /*静态调用*/ staticRedisTemplate.opsForValue().get("redisKey"); } }
参考博客:关于Spring/SpringBoot在静态工具类中注入Service的解决方案_Mr_chen的博客-CSDN博客_springboot 静态类注入