问题 & 背景
【问题描述】在开发中通过反射生成了类,反射类中注入的成员变量为null
【问题原因】因为反射生成的类没有交由springboot
管理
【问题解决】反射生成类后,需要交由spring
容器管理
代码
如果不交由spring
容器管理,打断点发现testService
为null
,执行testService.test()
报空指针异常
public class TestCompute implements ICompute {
@Autowired
TestService testService;
public void compute() {
testService.test();
}
}
Class<?> cls = null;
try {
cls = Class.forName(computeRule.toString());
// ICompute iCompute = (ICompute) cls.newInstance();
ICompute iCompute = (ICompute) SpringUtil.getBean(cls);
// 获取计算规则实例为空
if (iCompute == null) {
log.debug("====> class: {} is not fond", computeRule);
throw new ServiceUserTagException("class " + computeRule + " is not found");
}
return iCompute;
} catch (Exception e) {
log.error("class not found: {}, e: {}", computeRule, e);
throw new ServiceUserTagException("class not found " + computeRule);
}
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Slf4j
@Component
public class SpringUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if(SpringUtil.applicationContext == null) {
SpringUtil.applicationContext = applicationContext;
}
log.info("ApplicationContext配置成功,applicationContext对象:"+SpringUtil.applicationContext);
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
public static Object getBean(String name) {
return getApplicationContext().getBean(name);
}
public static <T> T getBean(Class<T> clazz) {
return getApplicationContext().getBean(clazz);
}
public static <T> T getBean(String name,Class<T> clazz) {
return getApplicationContext().getBean(name,clazz);
}
}
参考
【1】springBoot @Autowired注入对象为空原因总结:https://blog.csdn.net/sunjinjuan/article/details/87255551
网友评论