问题原因:因为使用反射方式执行方法时,该对象没有被Spring管理到,所以无法获取到spring内的对象。
问题解决:使用ApplicationContext从Spring容器内进行获取对象。
工具类:
@Component
public class SpringContextUtils implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
SpringContextUtils.applicationContext = applicationContext;
}
public static Object getBean(String name) {
return applicationContext.getBean(name);
}
public static <T> T getBean(Class<T> requiredType) {
return applicationContext.getBean(requiredType);
}
public static <T> T getBean(String name, Class<T> requiredType) {
return applicationContext.getBean(name, requiredType);
}
public static boolean containsBean(String name) {
return applicationContext.containsBean(name);
}
public static boolean isSingleton(String name) {
return applicationContext.isSingleton(name);
}
public static Class<? extends Object> getType(String name) {
return applicationContext.getType(name);
}
}
示例:
//反射调用无法直接使用spring注入的对象
TblBusinessOrderService bean = SpringContextUtils.getBean(TblBusinessOrderService.class);
bean.saveBatch(businessOrders);