您的位置:首页 > 移动开发

spring ApplicationContext 使用总结

2016-07-28 15:42 447 查看
1、Spring为ApplicationContext提供的3种实现分别为:ClassPathXmlApplicationContext,FileSystemXmlApplicationContext,XmlWebApplicationContext,其中XmlWebApplicationContext是专为Web工程定制的

FileSystemXmlApplicationContext方法对路径进行了处理:

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"})



3、classPath指的是编译后生成的classes目录

上面的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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: