注入Bean

spring getbean 方法分析

拟墨画扇 提交于 2020-03-18 11:26:18
某厂面试归来,发现自己落伍了!>>> 在最近的项目中,有个地方我们不得不实用getBean的方法,自己从Spring context中获取bean进行数据库操作。 方法一(效率低,极易出现bug,不推荐使用): 刚刚开始的时候,我们使用这中方式,但是在应用过程中发现此方式效率低下,而且极易出现bug。 在我们系统中会生成ehcache_auto_created_时间戳文件夹, <!-- lang: java --> String[] xmlCfg = new String[] {"classpath:/spring/applicationContext-service.xml", "classpath:/spring/applicationContext-util.xml", "classpath:/spring/applicationContext.xml"}; ApplicationContext context = new FileSystemXmlApplicationContext(xmlCfg); // 获取inspectionUtil bean inspectionUtil = (InspectionUtil) context.getBean("inspectionUtil"); 所以我google了一下,改用其他方法。 方法二(效率高,灵活性高,可复用,推荐使用):