通过ApplicationContextAware解决spring注解注入方式为null

我的问题是在监控一个门禁刷卡记录时遇到,service层调用时为null

在这里插入图片描述这个是我测试刷卡记录时debuuger模式下的注入都为null。网上大致搜了一下,因为这个类被new过了,所以不能注入。我找了一下代码发现在连接门禁的时候,被new 了。
在这里插入图片描述于是我换了一种注入方式,首先创建一个类叫ApplicationContextGetBeanHelper,实现ApplicationContextAware,在里面写获取bean的方法。

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class ApplicationContextGetBeanHelper implements ApplicationContextAware {

    private static ApplicationContext applicationContext;
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    public static Object getBean(String className) throws BeansException,IllegalArgumentException {
        if(className==null || className.length()<=0) {
            throw new IllegalArgumentException("className为空");
        }

        String beanName;
        if(className.length() > 1) {
            beanName = className.substring(0, 1).toLowerCase() + className.substring(1);
        } else {
            beanName = className.toLowerCase();
        }
        return applicationContext != null ? applicationContext.getBean(beanName) : null;
    }

    public static  <T> T getBean(Class<T> beanClass) throws BeansException,IllegalArgumentException {
        if(beanClass==null) {
            throw new IllegalArgumentException("beanClass为空");
        }
        return applicationContext != null ? applicationContext.getBean(beanClass) : null;
    }
}


然后注入方式就变成了,直接在方法里面注入
第一种:

  DeviceMapper deviceMapper = (DeviceMapper) ApplicationContextGetBeanHelper.getBean("deviceMapper");

第二种:

DeviceMapper bean = ApplicationContextGetBeanHelper.getBean(DeviceMapper.class);

后面就可以正常调用接口了。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值