java项目下,可以通过 new ClassPathXmlApplicationContext("ApplicationContext.xml");
web项目下,需通过监听器 Listener,初始化xml文件,否则就需要在大部分类中new ,容易内存溢出
- <?xml
version="1.0"
encoding="UTF-8"?>
- <web-app
version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
- <display-name>web 02</display-name>
- <welcome-file-list>
- <welcome-file>index.jsp</welcome-file>
- </welcome-file-list>
-
- <context-param>
- <param-name>contextConfigLocation</param-name>
- <!-- classpath代表类路径src,如是不写classpath则会直接去web-INF去找 -->
- <param-value>classpath:applicationContext.xml</param-value>
- </context-param>
- <listener>
- <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
- </listener>
- </web-app>
|
spring针对web开发的几种方式
例如一个考勤项目
1、三层架构,DB >> student\class >> servcice >>servlet
配置文件:applicationContext-Student.xml
applicationContext-service.xml
applicationContext-servlet.xml
2、按功能模块呀模块划分,DB >> student(包括service/servlet) \ class
配置文件:applicationContext-Student.xml
applicationContext-class.xml
加载多个配置文件
1、推荐方式
2\ 不推荐此类方法
Web.xml文件只需加载主配置文件,将其他附属配置文件用<import resource=""/>单个或者群居加入
- <?xml
version="1.0"
encoding="UTF-8"?>
- <beans
xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
- <import
resource="applicationContext-student.xml"/>
- <import
resource="applicationContext-class.xml"/>
- <import
resource="applicationContext-teacher.xml"/>
- <import
resource="applicationContext-*.xml"/>
-
- </beans>
|
Spring-web + servlet
web.xml配置监听器:目的是tomcat启动时自动初始化applicationContext.xml文件(IOC容器)
- <context-param>
- <param-name>contextConfigLocation</param-name>
- <!-- classpath代表类路径src -->
- <param-value>
- <!-- classpath:applicationContext-student.xml
classpath:applicationContext-class.xml classpath:applicationContext-teacher.xml -->
- classpath:applicationContext.xml
- </param-value>
- </context-param>
- <listener>
- <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
-
</listener>
|
//因为servlet和spring ioc是2个单独的容器,项目启动会自动初始化IOC容器。
//但是请求时有时servlet容器,所以还需在servlet容器中访问一次IOC容器。只需拿到最后的值。
- @Override
- public
void
init()
throws ServletException {
- //一种方式
- //ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml")
- //web开发常用方式
- ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
- ss = (StudentService) context.getBean("studentService");
- }
|