我们每次使用spring容器的时候,就需要创建一个spring容器,这样会占用许多内存。那么我们有什么方法可以解决这个问题呢?
在我们创建javaWeb容器的时候,会创建一个ServletContext对象,并且这个对象是唯一的,单例的,在JavaWeb容器关闭的时候才会销毁。因此,我们可以通过监听ServletContext的启动,当ServletContext启动的时候,我们就同时启动spring容器,并把spring容器放到ServletContext对象中,这样我们的spring容器也只启动一次,当我们需要使用spring容器的时候,就可以直接从ServletContext当中获取。
第一步:导入spring与web整合的对应版本的jar包
<!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
第二步:配置监听器,监听我们的web项目启动
<!-- needed for ContextLoaderListener -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- Bootstraps the root web application context before servlet initialization -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
第三步:定义自己的servlet,修改doGet方法,在servlet请求中获取spring容器
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//第一步:获取servletContext对象
ServletContext context = request.getServletContext();
//第二步:获取ApplicationContext对象
WebApplicationContext attribute = (WebApplicationContext) context.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
//第三步:获取JavaBean对象
CollectProperty bean = (CollectProperty) attribute.getBean("collectProperty");
}
第四步:在web.xml中设置servlet访问路径
<servlet>
<description></description>
<display-name>ContextServlet</display-name>
<servlet-name>ContextServlet</servlet-name>
<servlet-class>com.itheima.demo.ContextServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ContextServlet</servlet-name>
<url-pattern>/ContextServlet</url-pattern>
</servlet-mapping>
:第五步:测试
访问web.xml中配置的地址,可以得到JavaBean对象
网友评论