痛点
我们在开发 SpringBoot 项目时,当对象不是通过 @Autowird 常用的 MVC 三层架构依赖注入进来时,在使用的时候会报NPE异常。
使用场景
AService 中调用 BUtil工具类中的方法,BUtil工具类中的方法此时需要查询数据库操作,查询数据库操作需要使用BService 中的 select() 接口,此时我们在BUtil 中使用 @Autowird BService bService 是不能成功注入的。
解决办法
通过实现 ApplicationContextAware 接口从容器中获取对象
反射工具类
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
* 反射获取 spring 容器中的bean
*/
@Component
public class ReflectUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if (ReflectUtil.applicationContext == null) {
ReflectUtil.applicationContext = applicationContext;
}
}
/**
* 获取applicationContext
* @return
*/
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
/**
* 通过name获取 Bean.
* @param name
* @return
*/
public static Object getBean(String name) {
return getApplicationContext().getBean(name);
}
/**
* 通过class获取Bean.
* @param clazz
* @return
*/
public static <T> T getBean(Class<T> clazz) {
return getApplicationContext().getBean(clazz);
}
/**
* 通过name,以及Clazz返回指定的Bean
* @param name 容器名
* @param clazz 对象Class
* @return
*/
public static <T> T getBean(String name, Class<T> clazz) {
return getApplicationContext().getBean(name, clazz);
}
}
使用方法
private void test(t) {
DrmOperation drmOperation = ReflectUtil.getBean(DrmOperationManager.class).get(drmTask.getOperationId());
}