SpringBoot项目中的@Component注解下的类无法@Autowired注入的时候为null

前言

本地在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");
  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值