核心思想是无法自动注入就自己手动new
和单例模式写法一致
创建一个私有的属性
private WaybillUtils waybillUtils;
提供一个
@Override
public R check(List<WaybillImportVo> waybillVo) {
this.waybillUtils = new WaybillUtilsImpl();
//本类中的其他方法
check();
}
check(){
//这里就能使用该属性了
waybillUtils.xxxx();
}
这样就能用new出来的类了
用重载的方式写方便代码重用
但是这样就存在一个问题
手动new出来的类依然是脱离spring的
这里new出来的类依然是不能自动注入里面的xxxService或xxxDao
那么正确的思路是什么呢?
**
springapplicationContext_40">使用spring的applicationContext,来获取你想要使用的类
**
比如这里我想用WaybillUtils,但是WaybillUtils是null,
就可以使用下面的代码
ApplicationContext applicationContext = SpringContextHolder.getApplicationContext();
this.waybillUtils = applicationContext.getBean("waybillUtilsImpl", WaybillUtilsImpl.class);
需要注意的是spring自动创建的类名首字母是小写
另外想使用上面的这个方法,需要把下面这个类在自己项目中创建,并且要能被spring扫描到.(@Component注解),否则也是无效的
/**
* 以静态变量保存Spring ApplicationContext, 可在任何代码任何地方任何时候取出ApplicaitonContext.
*
*/
@Component
public class SpringContextHolder implements ApplicationContextAware, DisposableBean {
private static ApplicationContext applicationContext = null;
private static Logger logger = LoggerFactory.getLogger(SpringContextHolder.class);
/**
* 取得存储在静态变量中的ApplicationContext.
*/
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
/**
* 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
*/
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) {
return (T) applicationContext.getBean(name);
}
/**
* 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
*/
public static <T> T getBean(Class<T> requiredType) {
return applicationContext.getBean(requiredType);
}
/**
* 清除SpringContextHolder中的ApplicationContext为Null.
*/
public static void clearHolder() {
logger.debug("清除SpringContextHolder中的ApplicationContext:" + applicationContext);
applicationContext = null;
}
/**
* 实现ApplicationContextAware接口, 注入Context到静态变量中.
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
logger.debug("注入ApplicationContext到SpringContextHolder:" + applicationContext);
if (SpringContextHolder.applicationContext != null) {
logger.warn("SpringContextHolder中的ApplicationContext被覆盖, 原有ApplicationContext为:"
+ SpringContextHolder.applicationContext);
}
SpringContextHolder.applicationContext = applicationContext; //NOSONAR
}
/**
* 实现DisposableBean接口, 在Context关闭时清理静态变量.
*/
@Override
public void destroy() throws Exception {
SpringContextHolder.clearHolder();
}
}