如何让Spring容器在项目运行中只创建一次?

容器在项目中应该只创建一次,而不应该每次有请求就创建一个容器,因此可以在项目中进行以下操作,节省资源

  1. 导包
    在这里插入图片描述
    2.在web.xml文件中进行配置
<listener>
      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
 <context-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:applicationContext.xml</param-value>
</context-param>

其中的原理是把容器跟ServletContext进行绑定,这样创建web项目的时候就会自动创建一个容器

之后要获得容器就从Application域获得,先获得ServletContext实例,再用Spring内置的方法WebApplicationContextUtils.getWebApplicationContext(sc)来获取容器

ServletContext sc = ServletActionContext.getServletContext();
WebApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(sc);
发布了38 篇原创文章 · 获赞 11 · 访问量 1792

猜你喜欢

转载自blog.csdn.net/weixin_44247784/article/details/102509633