前言
本地在springboot环境下搭建接口防刷项目时候,封装一个通用的redis工具类,在带有@componet的拦截器的类使用@autowired注入RedisUtil的时候为null,也就是没有注入成功,或者说此类在bean加载之前就被调用了。下面提供了两种解决办法供大家参考。
1.使用@PostConstruct注解,将需要注入的类添加到静态变量中
示例代码:
// redis工具类
@Component
public class RedisUtil {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
.....
}
// 拦截器
@Component
public class AccessLimitInterceptor extends HandlerInterceptorAdapter {
@Autowired
RedisUtil redisUtil;
// 解决@Component注解下@Autowired的类为null
public static AccessLimitInterceptor accessLimitInterceptor;
// 将需要注入的类添加到静态变量中
@PostConstruct
public void init() {
accessLimitInterceptor = this;
accessLimitInterceptor.redisUtil = this.redisUtil;
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object handler) throws Exception {
// 通过这种方式进行调用
System.out.println(accessLimitInterceptor.redisUtil);
}
}
备注:@PostConstruct这个注解的具体作用就是:
注解在方法上,表示此方法是在Spring实例化该bean之后马上执行此方法,之后才会去实例化其他bean。
这样在Spring实例化AccessLimitInterceptor之后,马上执行此方法,初始化accessLimitInterceptor静态对象和成员变量redisUtil。
2.编写工具类实现ApplicationContextAware接口,重写setApplicationContext方法
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
* <p>获取java bean的工具</p>
*
* @author xqh
* @create 2021/3/11 10:25
*/
@Component
public class ApplicationContextUtils implements ApplicationContextAware {
private static ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.context = applicationContext;
}
/**
* @param beanName
* @return
*/
public static Object getBean(String beanName) {
return context.getBean(beanName);
}
}
// 通过这种方法进行调用
RedisUtil redisUtil = (RedisUtil) ApplicationContextUtils.getBean("redisUtil");