将Spring容器跟随系统启动并获取容器对象

时间:2023-03-08 21:44:30

将Spring容器随系统启动的方法:

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