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

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

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