spring ApplicationContext 使用总结

本文详细介绍了Spring框架中的三种ApplicationContext实现:ClassPathXmlApplicationContext、FileSystemXmlApplicationContext和XmlWebApplicationContext,并展示了如何通过XML配置文件及注解方式来初始化这些上下文。此外,还讲解了如何通过Maven配置资源文件的加载。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值