首先还是我们的需求式开场白。在web项目中如何使用spring开发。如果使用 new ClassPathXmlApplicationContext 将每一次都加载xml,相当于每一次都创建spring容器。而真实开发中,容器只有一份。之后重复的从spring容器中获取内容。
自动加载配置文件,生成spring容器,并将其存放到ServletContext作用域中。Spring提供监听器程序ContextLoaderListener (ServletContextListener实现),tomcat启动时执行。启动时加载配置文件。
来段小栗子演示
service层(为了方便,直接来):
public class UserService
{
public void addUser()
{
System.out.println("add user");
}
}
然后去applicationContext.xml配置bean:
<bean id="userService" class="com.canyugan.service.UserService">
</bean>
在index.jsp写上我们的测试,直接点击页面,servlet处理addUser方法,并在服务器输出:
<body>
<a href="${pageContext.request.contextPath}/HelloServlet">点我</a>
</body>
<!--
设置web的全局初始化参数 设置配置文件的位置
name是固定值 class表示类路径
-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- 配置监听器 加载spring配置文件 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
此处需要注意一下,在只配监听器的情况下,你会很幸运的遇到一个Bug。来看看Bug长啥样:
Caused by: java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/applicationContext.xml]
什么意思?找不到文件位置。我们还需要配置文件位置。所以就有了上面我们配置的那段xml
public class HelloServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
//方式1:手动从servletcontext作用域获取内容
/*WebApplicationContext webApplicationContext=
(WebApplicationContext) this.getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);*/
//方式2:提供工具类
WebApplicationContext webApplicationContext=WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
UserService userService=(UserService) webApplicationContext.getBean("userService");
userService.addUser();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
doGet(request, response);
}
}
至此,大功告成。