在Web项目中整合Spring框架
需求:
由于基于Spring思想来进行项目开发,将来好扩展,好维护。要基于Spring的思想来开发,关键点就在于让Spring来管理程序中的一些对象。
分析一下,对于一个项目来说,哪些对象适合让Spring来管理:
- 实体 domain 对象 不需要Spring来管理,因为程序中总会随时创建domain的实例
- Dao层对象 , 需要。
- Service层对象, 需要。
- 异常, 不需要。
- util对象 , 不需要
- serlvet , 不需要,轮不到你管
- 数据库连接对象 , 需要。
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-AyVvbb67-1600247653527)(imges/image-20200826160847092.png)]
存在的问题
如何解决容器创建的问题呢?
- 理想的做法,是整个Web程序存续期间只创建一次Spring容器。
思考:
- 将创建好的Spring容器放在**一个地方(ServletContext)**存起来,用的时候去那里获取。
- 在Tomcat启动的时候,放进去最好。 且在Tomcat停止时,关闭容器也最好。
- 使用ServletContextListener来做这个事情在好不过了。
public class SpringContextListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
// tomcat启动时
ApplicationContext context = new ClassPathXmlApplicationContext(
"classpath:com/example/crud/spring-crud.xml");
servletContextEvent.getServletContext().setAttribute("SPRING", context);
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
//tomcat停止时
ConfigurableApplicationContext spring = (ConfigurableApplicationContext) servletContextEvent.
getServletContext().getAttribute("SPRING");
spring.close();
}
}
解决办法
其实,Spring框架早就很贴心的想到了Web集成的场景。意味着它已经内置了类似功能的监听器。
另外,在Web环境下,其实还有一种基于web目录的XML配置文件的容器。前提条件是:
- 项目中要引入 spring 的 web 模块。
- 使用
XmlWebApplicationContext
容器的实现。
//基于web目录的XML配置
XmlWebApplicationContext context = new XmlWebApplicationContext();
// 所有容器,带参的构造方法 new完之后,就会自动启动。
// 所有容器,不带参的构造方法,new 完之后,并不会自动启动,需要我们手工启动。
//XmlWebApplicationContext 这种容器的实现,除了支持类路径,还支持web路径
// context.setConfigLocation("classpath:com/example/crud/spring-crud.xml");
context.setConfigLocation("/WEB-INF/spring-crud.xml"); //服务器路径(web目录)
context.setServletContext(servletContextEvent.getServletContext()); //设置application域对象
context.refresh();//启动容器
Spring提供的这个标准的监听器的名字叫: 背会 ContextLoaderListener
<!-- 通过 ServletContext 参数的形式 接收spring的配置文件 -->
<context-param>
<!--参数名: 必须背会,不能瞎写-->
<param-name>contextConfigLocation</param-name>
<!-- <param-value>/WEB-INF/spring-crud.xml</param-value>-->
<param-value>classpath:com/example/crud/spring-crud.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
那么,用了它的监听器以后,如何获取它所创建的Spring容器(XmlWebApplicationContext
)
- 它存的key就是
WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE
- 显然Spring也考虑到你记住那个key 不太现实,
- 背会:它提供了一个工具类直接获取
WebApplicationContextUtils
- getWebApplicationContext
- findWebApplicationContext
- 背会:它提供了一个工具类直接获取