spring工程里,在controller,service以外的普通类里获取service,bean等类,可以通过上下文环境 ApplicationContext 做到。
见证奇迹的时刻到了:
private static ApplicationContext applicationContext = new FileSystemXmlApplicationContext("classpath:spring-context.xml");
private ISmsService smsService = applicationContext.getBean(ISmsService.class);
注意:classpath:spring-context.xml,这里的配置文件位置一定要写正确,否则读取不到配置文件,当然就拿不到类了。
本文介绍如何在Spring项目中,于Controller和服务层之外的普通类里通过ApplicationContext获取Bean实例,如Service组件。提供了具体实现代码,并强调了配置文件路径的重要性。
1474





