我们每次使用spring容器的时候,就需要创建一个spring容器,这样会占用许多内存。那么我们有什么方法可以解决这个问题呢?
在我们创建javaWeb容器的时候,会创建一个ServletContext对象,并且这个对象是唯一的,单例的,在JavaWeb容器关闭的时候才会销毁。因此,我们可以通过监听ServletContext的启动,当ServletContext启动的时候,我们就同时启动spring容器,并把spring容器放到ServletContext对象中,这样我们的spring容器也只启动一次,当我们需要使用spring容器的时候,就可以直接从ServletContext当中获取。
第一步:导入spring与web整合的对应版本的jar包
org.springframework
spring-web
4.2.4.RELEASE
javax.servlet
javax.servlet-api
3.1.0
provided
第二步:配置监听器,监听我们的web项目启动
contextConfigLocation
classpath:applicationContext.xml
org.springframework.web.context.ContextLoaderListener
第三步:定义自己的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访问路径
ContextServlet
ContextServlet
com.itheima.demo.ContextServlet
ContextServlet
/ContextServlet
:第五步:测试
访问web.xml中配置的地址,可以得到JavaBean对象