Spring通过ApplicationContext主动获取bean的方法讲解
问题1:
有个异步线程Runnable里面需要用到dao,无法通过AutoWired和compoment注解传递进来。
于是希望通过Springcontext主动去获取bean。
问题2:
getBean(name)获取失败。
解决:
默认的dao的name=类名(首字母小写)
例如:
接口名称:TemplateDao则getName(“templateDao”)即可
通用的SpringContextUtil获取Bean
1.实现ApplicationContextAware接口
/** *spring上下文配置 *@authorMingchenchen * */ @Component publicclassSpringContextUtilimplementsApplicationContextAware{ privatestaticLoggerlogger=Logger.getLogger(SpringContextUtil.class); privatestaticApplicationContextapplicationContext=null; publicvoidsetApplicationContext(ApplicationContextapplicationContext)throwsBeansException { logger.info("------SpringContextUtilsetApplicationContext-------"); SpringContextUtil.applicationContext=applicationContext; } publicstaticApplicationContextgetApplicationContext(){ returnapplicationContext; } /** *注意beanname默认=类名(首字母小写) *例如:A8sClusterDao=getBean("k8sClusterDao") *@paramname *@return *@throwsBeansException */ publicstaticObjectgetBean(Stringname)throwsBeansException{ returnapplicationContext.getBean(name); } /** *根据类名获取到bean *@param*@paramclazz *@return *@throwsBeansException */ @SuppressWarnings("unchecked") publicstatic TgetBeanByName(Class clazz)throwsBeansException{ try{ char[]cs=clazz.getSimpleName().toCharArray(); cs[0]+=32;//首字母大写到小写 return(T)applicationContext.getBean(String.valueOf(cs)); }catch(Exceptione){ e.printStackTrace(); returnnull; } } publicstaticbooleancontainsBean(Stringname){ returnapplicationContext.containsBean(name); } publicstaticbooleanisSingleton(Stringname)throwsNoSuchBeanDefinitionException{ returnapplicationContext.isSingleton(name); } }
2.在web项目中的web.xml中配置加载Spring容器的Listener
org.springframework.web.context.ContextLoaderListener
getBeanByName(Classclazz)
这个方法更好使用,不过需要注意Dao和service的impl里面需要配置好名称为@Service(“myService”)
规则为接口Service的类名首字母小写。
第二种方式:
目前又做了个系统初始化的东东SystemInit,然后发现上面的getBean()用不了了。看了下发现是因为在系统初始化的时候SpringContextUtil还没有初始化,导致在SystemInit类里面的东西getBean()失败。
于是小改造了下,把ApplicationContextAware放在SystemInit类,然后注入到SpringContextUtil,这样就保证了在执行系统初始化方法之前,applicationContext一定不是null。
/** *spring上下文配置 *@authorMingchenchen * */ publicclassSpringContextUtil{ privatestaticLoggerlogger=Logger.getLogger(SpringContextUtil.class); //@Autowired沿用springTest的这种方法是否会更好? //ApplicationContextctx; privatestaticApplicationContextapplicationContext=null; publicstaticvoidsetApplicationContext(ApplicationContextapplicationContext)throwsBeansException{ logger.info("------SpringContextUtilsetApplicationContext-------"); SpringContextUtil.applicationContext=applicationContext; } //注意此处变成了static publicstaticApplicationContextgetApplicationContext(){ returnapplicationContext; } /** *注意beanname默认=类名(首字母小写) *例如:A8sClusterDao=getBean("k8sClusterDao") *@paramname *@return *@throwsBeansException */ publicstaticObjectgetBean(Stringname)throwsBeansException{ returnapplicationContext.getBean(name); } /** *根据类名获取到bean *@param*@paramclazz *@return *@throwsBeansException */ @SuppressWarnings("unchecked") publicstatic TgetBeanByName(Class clazz)throwsBeansException{ try{ char[]cs=clazz.getSimpleName().toCharArray(); cs[0]+=32;//首字母大写到小写 return(T)applicationContext.getBean(String.valueOf(cs)); }catch(Exceptione){ e.printStackTrace(); returnnull; } } publicstaticbooleancontainsBean(Stringname){ returnapplicationContext.containsBean(name); } publicstaticbooleanisSingleton(Stringname)throwsNoSuchBeanDefinitionException{ returnapplicationContext.isSingleton(name); } } /** *Descripties:系统初始化 *@authorwangkaiping *2016年5月23日上午11:58:09 */ @Component publicclassSystemInitimplementsInitializingBean,ApplicationContextAware{ privatestaticLoggerlogger=Logger.getLogger(SystemInit.class); @Autowired privateClusterDaoclusterDao; @Override publicvoidafterPropertiesSet()throwsException{ logger.info("--------------系统初始化中-------------------"); initClusterCache();//初始化集群数据必须最开始完成 initRefreshAppStatusTask(); initUpdateAppStatusToDB(); initUpdateSession(); logger.info("--------------系统初始化完成-------------------"); } /** *1.初始化集群数据 */ privatevoidinitClusterCache(){ logger.info("1.初始化集群信息到缓存中:ClusterCache开始"); //查询数据库所有的集群数据 List allClusterInfoList=clusterDao.selectAll(ClusterEntity.class,"delete_flag=0"); for(ClusterEntityk8sClusterEntity:allClusterInfoList){ ClusterCache.put(k8sClusterEntity.getUuid(),k8sClusterEntity);//存入缓存 } logger.info("1.初始化集群信息到缓存中:ClusterCache完成,总共"+allClusterInfoList.size()+"条数据"); } /** *2.初始化异步任务:刷新所有应用状态 */ privatevoidinitRefreshAppStatusTask(){ logger.info("2.初始化任务:RefreshAllAppStatusTask刷新应用下的k8s的pod状态并存入待更新队列"); RefreshAppStatusExcutor.init(); logger.info("2.初始化任务:RefreshAllAppStatusTask完成"); } /** *3.初始化异步任务:更新状态到数据库 */ privatevoidinitUpdateAppStatusToDB(){ logger.info("3.初始化任务:RefreshToDBTask从待更新Appinstance队列取出数据并更新数据库"); UpdateAppStatusToDBExcutor.init(); logger.info("3.初始化任务:RefreshToDBTask完成"); } /** *4.初始化异步任务:更新用户的所有session */ privatevoidinitUpdateSession(){ logger.info("4.初始化任务:更新session开始"); UserSessionUpdateExcutor.init(); logger.info("4.初始化任务:更新session结束"); } //////////////////////////////////////////////////////////////// //此方法一定不要写成static @Override publicvoidsetApplicationContext(ApplicationContextapplicationContext) throwsBeansException{ //实际上是把applicationContext传入到了SpringContextUtil里面 SpringContextUtil.setApplicationContext(applicationContext); } }
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对毛票票的支持。如果你想了解更多相关内容请查看下面相关链接