在Web项目中创建使用Spring框架
1.Spring容器的创建
因为Spring容器在整个web项目中只需要创建一次,并且满足在项目开始时创建,在项目销毁时销毁,所以考虑Spring容器的创建/销毁时机和存放位置:
- 存放位置:ServletContext域
- 创建/销毁时机:利用ServletContext监听器在ServletContext创建时创建,在ServletContext销毁时销毁
1.1创建监听类
SpringContextListener
public class SpringContextListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
System.out.println("ServletContext被创建");
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
System.out.println("servletContext被销毁");
}
}
1.2 配置web.xml监听
<?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">
<listener>
<listener-class>com.example.web.listener.SpringContextListener</listener-class>
</listener>
</web-app>
1.3 创建想要管理的Spring xml文件
<?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 name="bean1" class="com.example.spring.Bean1">
<property name="num" value="#{T(java.lang.Math).random()}"></property>