方法一:在初始化时保存ApplicationContext对象
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
applicationContext.getBean("beanId");
这种方法会初始化Spring容器,重新加载applicationContext.xml文件,如果配置文件中有一些线程类或者定时任务,会执行两次。
方法二:不依赖于servlet,不需要注入的方式
WebApplicationContext ac = ContextLoader.getCurrentWebApplicationContext();
TestService testService= (TestService) wac.getBean("testService");
这种方法得等到服务器启动完成