方法一:在初始化时保存ApplicationContext对象
- ApplicationContext ac = new FileSystemXmlApplicationContext("applicationContext.xml");
- ac.getBean("userService");//比如:<bean id="userService" class="com.cloud.service.impl.UserServiceImpl"></bean>
方法二:通过Spring提供的工具类获取ApplicationContext对象
- ApplicationContext ac1 = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletContext sc);
- ApplicationContext ac2 = WebApplicationContextUtils.getWebApplicationContext(ServletContext sc);
- ac1.getBean("beanId");
- ac2.getBean("beanId");
方法三:通过Spring提供的ContextLoader
- WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
- wac.getBean(beanID);
- 例子:BookDao bookDao = (BookDao) ContextLoader.getCurrentWebApplicationContext().getBean("bookDao");
Bok bok = bookDao.getBok(1);