获取spring bean的几种方法

方法一:在初始化时保存ApplicationContext对象

  1. ApplicationContext ac = new FileSystemXmlApplicationContext("applicationContext.xml");
  2. ac.getBean("userService");//比如:<bean id="userService" class="com.cloud.service.impl.UserServiceImpl"></bean>

方法二:通过Spring提供的工具类获取ApplicationContext对象

  1. ApplicationContext ac1 = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletContext sc);
  2. ApplicationContext ac2 = WebApplicationContextUtils.getWebApplicationContext(ServletContext sc);
  3. ac1.getBean("beanId");
  4. ac2.getBean("beanId");

方法三:通过Spring提供的ContextLoader

  1. WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
  2. wac.getBean(beanID);
  3. 例子:BookDao bookDao = (BookDao) ContextLoader.getCurrentWebApplicationContext().getBean("bookDao");
               Bok bok = bookDao.getBok(1);

猜你喜欢

转载自blog.csdn.net/u014450465/article/details/87896153