文章目录
Java获取Bean的几种方式
1、在初始化时保存ApplicationContext对象
//Spring框架的独立应用程序,需要程序通过配置文件初始化Spring,获取失败时抛出异常
ApplicationContext ac = new FileSystemXmlApplicationContext("applicationContext.xml");
ac.getBean("userService");
//application.xml配置:
<bean id="userService" class="com.example.service.impl.UserServiceImpl"></bean>
2、通过Spring提供的utils类获取ApplicationContext对象
// Spring中获取ServletContext对象,普通类中可以这样获取
ServletContext sc = ContextLoader.getCurrentWebApplicationContext().getServletContext();
// servlet中可以这样获取
ServletContext sc = request