原创转载请注明出处:http://agilestyle.iteye.com/admin/blogs/2325616
1.Spring配置文件在类路径下面
即配置文件在“src/main/resources”目录下,可以通过如下代码获取相应的bean
AbstractApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
context.close();//释放资源
整合JUnit,可以通过如下代码进行容器初始化
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:applicationContext.xml"})
注意:
关于ApplicationContext的初始化
一、推荐的初始化方法:
(1).在独立应用程序中,获取ApplicationContext:
AbstractApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
context.close();//释放资源
(2).在web环境中,获取ApplicationContext:
a).
ServletContext servletContext = request.getSession().getServletContext();
ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext);
b).
String contextPath = "org.springframework.web.context.WebApplicationContext.ROOT";
WebApplicationContext context = request.getSession().getServletContext().getAttribute(contextPath);
二、不推荐的方法:(这种写法不仅仅耗内存,占资源,而且如果数据库连接太多,很容易造成系统运行的缓慢甚至终止)
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
2.Spring配置文件在WEB-INF下面
即配置文件在“src/main/webapp/WEB-INF”目录下,可以通过如下代码获取相应的bean
AbstractApplicationContext context = new FileSystemXmlApplicationContext("/src/main/webapp/WEB-INF/applicationContext.xml");
context.close();
整合JUnit,可以通过如下代码进行容器初始化
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"file:src/main/webapp/WEB-INF/applicationContext.xml"})