文章目录
一、概述
我们有可能要在普通类里获取bean实例,比如工具类。
二、方式
1、初始化时保存ApplicationContext对象
通过配置文件初始化。
ApplicationContext ac = new FileSystemXmlApplicationContext("applicationContext.xml");
ac.getBean("userService");
...
<bean id="userService" class="per.helen.user.service.UserService">
...
2、Spring工具类ApplicationContext
通过ServletContext对象获取ApplicationContext对象。
ApplicationContext ac1 = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletContext sc); //失败时抛出异常
ApplicationContext ac2 = WebApplicationContextUtils.getWebApplicationContext(Servlet sc; //失败时返回null
ac1.getBean("userService");
ac2.getBean("userService");
3、继承抽象类ApplicationObjectSupport
该抽象类提供了getApplicationContext()方法。
Spring初始化时,会通过该抽象类的setApplicationContext()方法把applicationContext对象注入。
4、继承抽象类WebApplicationObjectSupport
该抽象类也提供了getApplicationContext()方法。
5、实现接口ApplicationContextAware
实现该接口的setApplicationContext(ApplicationContext context)方法,保存ApplicationContext对象。
Spring初始化时,会通过该方法把ApplicationContext对象注入。
3、4、5方法记得在applicationContext.xml配置这些个实现类。
6、Spring的ContextLoader
不依赖Servlet,无需注入,但是Server启动时,Spring容器初始化的时候,不能通过下面的方法获取Spring容器,会得到一个null。
WebApplicationContext ac = ContextLoader.getCurrentWebApplicationContext();
ac.getBean("userService");