将Spring容器随系统启动的方法:
- 在web.xml中配置监听器,监听的对象为ContextLoaderListener
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
- 在web.xml中配置context参数以便容器启动时便查找到spring的配置文件
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
- 获取容器对象并从容器中取出对象
WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
//WebApplicationContextUtils.getWebApplicationContext(sc);//这种方式获取需要传入一个ServletContext对象
User user = (User) webApplicationContext.getBean("user");
System.out.println(user);