静态方法调用Spring容器中的bean

自定义工具类中有时需要调用容器中的bean,因为是静态方法,声明注入bean时必须用static修饰,此时会出现注入异常。 例如:

@Component
public class CacheUtil {
          
   

	private static RedisTemplate<String, Serializable> redisTemplate;
	
	public static Object get(String key) {
          
   
    	return redisTemplate.opsForValue().get(key);
	}
}

解决方法一:使用@Autowired注解构造函数

@Autowired
public CacheUtil(RedisTemplate<String, Serializable> redisTemplate) {
          
   
    CacheUtil.redisTemplate= redisTemplate;
}

方法二:使用@Autowired注解setXxx注入

@Autowired
public void setRedisTemplate(RedisTemplate<String, Serializable> redisTemplate) {
          
   
    CacheUtil.redisTemplate = redisTemplate;
}

方法三:使用 @PostConstruct 注解

@Autowired
private CacheImpl cacheImpl;

private static CacheUtil cacheUtil ;

@PostConstruct
public void init() {
          
   
    cacheUtil = this;
    cacheUtil.cacheImpl= this.cacheImpl;
}
经验分享 程序员 微信小程序 职场和发展