1、Spring为ApplicationContext提供的3种实现分别为:ClassPathXmlApplicationContext,FileSystemXmlApplicationContext,XmlWebApplicationContext,其中XmlWebApplicationContext是专为Web工程定制的
protected Resource getResourceByPath(String path) {
if(path != null && path.startsWith("/")) {
path = path.substring(1);
}
return new FileSystemResource(path);
}
}
下面两种写法是一样的:
ApplicationContext context = new FileSystemXmlApplicationContext("/src/main/resources/spring/applicationContext.xml");
ApplicationContext context = new FileSystemXmlApplicationContext("src/main/resources/spring/applicationContext.xml");
2、可以使用注解的方式代替上面方式
//@RunWith(SpringJUnit4ClassRunner.class) //使用注解方式
//@ContextConfiguration(locations = {"/spring/applicationContext.xml"}) //使用注解方式 classpath 下面的路径
//或者
//@ContextConfiguration(locations = {"classpath:applicationContext.xml"}) //使用注解方式
使用文件路径注解方式:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"file:src/main/webapp/WEB-INF/applicationContext.xml"})
上面的classes目录中包含的文件和目录可以通过maven的build段配置
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>2.5</version>
<configuration>
<encoding>${build.file.encoding}</encoding>
</configuration>
</plugin>
</plugins>
</build>