我的问题是在监控一个门禁刷卡记录时遇到,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);
后面就可以正常调用接口了。