之前java项目中问题:
-
手动创建Spring容器
-
在其他类需要spring容器, 重复创建
Spring容器对象的scope: 整个项目只有一个, 创建之后不能销毁, 在其他类共享这个容器对象
整合目的:
-
自动创建Spring容器(在服务(Tomcat)启动的时候)
-
监听tomcat启动行为, 一旦Tomcat启动触发执行相对应的代码(创建Spring容器), 使用的就是监听器
javaWeb中, 三剑客: Servlet(接收请求,处理请求), Filter(拦截请求), listener(监听器,监听某个行为, 触发这个行为, 自动执行对应代码,类似前端的事件机制 )
-
把Spring容器保存起来, 在其他类重复使用
Spring容器对象保存到哪? Application域
保存域中(page域,request域, session域, application域[ServletContext])
整合步骤:
-
创建maven的web项目
-
在pom.xml文件添加 与web整合的依赖: spring web
<!--spring-web--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency>
-
在web.xml文件中配置监听器(监听服务器启动), 这个监听器在Spring-web提供了
ApplicationContext接口:
-
ClassPathXmlApplicationContext
-
AnnotationConfigApplicationContext
-
WebApplicationContext:(web环境下的SPring容器)
<!--配置监听器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--指定spring的配置文件-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:beans.xml</param-value>
</context-param>
把Servlet交给spring管理, service交给Spring管理, 在Servlet注入service, 得到是null
Spring容器中有这个些bean
项目中有几个StudentServlet对象?
有两个:
-
使用@Controller注解, 把Servlet对象交给Spring管理, Spring容器有一个
-
因为是Servlet类, 请求servlet对象, Tomcat为我们创建Servlet对象, 保存Tomcat的Servlet容器; 有一个 获取Spring容器的方法:
//ServletContext application = this.getServletContext();
//ApplicationContext applicationContext = (ApplicationContext)application.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
//提供一个工具类, 获取Spring容器的工具类
WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
解决方案: 只能在Servlet中,手动getBean获取Service对象
Servlet一定不要交给Spring管理