spring为ApplicationContext提供的3种实现分别为:ClassPathXmlApplicationContext,FileSystemXmlApplicationContext和 XmlWebApplicationContext,其中XmlWebApplicationContext是专为Web工程定制的。使用举例如下:
1. FileSystemXmlApplicationContext
eg1. ApplicationContext ctx = new FileSystemXmlApplicationContext("bean.xml"); //加载单个配置文件
eg2.
String[] locations = {"bean1.xml", "bean2.xml", "bean3.xml"};
ApplicationContext ctx = new FileSystemXmlApplicationContext(locations ); //加载单个配置文件
eg3.
ApplicationContext ctx =new FileSystemXmlApplicationContext("D:/project/bean.xml");//根据具体路径加载文件
2. ClassPathXmlApplicationContext
eg1. ApplicationContext ctx = new ClassPathXmlApplicationContext("bean.xml");
eg2.
String[] locations = {"bean1.xml", "bean2.xml", "bean3.xml"};
ApplicationContext ctx = new ClassPathXmlApplication(locations);
注:其中FileSystemXmlApplicationContext和ClassPathXmlApplicationContext与BeanFactory的xml文件定位方式一样是基于路径的。
3. XmlWebApplicationContext
eg1. ServletContext servletContext = request.getSession().getServletContext();
ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);
//web下得到路径一般如下:
上文中说过,当前用户目录,即相对于System.getProperty("user.dir")返回的路径。
对于JavaEE服务器,这可能是服务器的某个路径,这个并没有统一的规范!
而不是我们发布的Web应用程序的根目录!
这样,在Web应用程序中,我们绝对不能使用相对于当前用户目录的相对路径。
在Web应用程序中,我们一般通过ServletContext.getRealPath("/")方法得到Web应用程序的根目录的绝对路径。
这样,我们只需要提供相对于Web应用程序根目录的路径,就可以构建出定位资源的绝对路径。
这是我们开发Web应用程序时一般所采取的策略。
举例,在servlet中要想获取spring容器管理的对象就用如下方式即可
package com.liangs.jdbcTemplate;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
public class UserServlet extends HttpServlet {
private UserDAO dao;
public UserServlet() {
super();
}
public void destroy() {
super.destroy();
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println(dao);
}
public void init() throws ServletException {
WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
this.dao = (UserDAO) wac.getBean("userDAO");
System.out.println(dao);
}
}
1375

被折叠的 条评论
为什么被折叠?



