1.使用方法
(1) 需要额外加入的 jar 包:
spring-web-5.1.8.RELEASE.jar
spring-webmvc-5.1.8.RELEASE.jar
(2) Spring 的配置文件相同
<?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">
<bean id="person" class="bean.Person">
<property name="name" value="憨憨"/>
</bean>
</beans>
(3) 创建 IOC 容器
① 非 WEB 应用在 main 方法中直接创建
② 应该在 WEB 应用被服务器加载时就创建 IOC 容器:
在(监听器) ServletContextListener # contextInitialized(ServletContextEvent sce) 方法中创建 IOC 容器.
public class SpringListener implements ServletContextListener {
public SpringListener() {
}
@Override
public void contextInitialized(ServletContextEvent sce) {
//1. 获取 Spring 配置文件的名称.
ServletContext servletContext =sce.getServletContext();
String config = servletContext.getInitParameter("contextConfigLocation");
//2. 创建 IOC 容器
ApplicationContext ctx = new ClassPathXmlApplicationContext(config);
//3. 把 IOC 容器放在 ServletContext 的一个属性中.
servletContext.setAttribute("ApplicationContext", ctx);
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
}
}
(4) 在 WEB 应用的其他组件中如何来访问 IOC 容器
在 ServletContextListener # contextInitialized(ServletContextEvent sce) 方法中创建 IOC 容器后,
可以把其放在ServletContext(即 application 域)的一个属性中.
@WebServlet("/TestServlet")
public class testServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1. 从 application 域对象中得到 IOC 容器的引用
ServletContext servletContext = getServletConfig().getServletContext();
ApplicationContext ctx = (ApplicationContext) servletContext.getAttribute("ApplicationContext");
//2. 从 IOC 容器中得到需要的 bean
Person person = (Person) ctx.getBean("person");
person.Hello();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
注:实际上, Spring 配置文件的名字和位置应该也是可配置的! 将其配置到当前 WEB 应用的初始化参数中较为合适.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!--配置Spring配置文件的名称和位置-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:application.xml</param-value>
</context-param>
<!--启动 IOC 容器的 SpringListener -->
<listener>
<listener-class> listener.SpringListener</listener-class>
</listener>
</web-app>