ClassPathXmlApplicationContext资源加载

xml文件绝对路径

这种很简单绝对路径只要没错idea就直接可以显示它的路径,构建的是configLocations

java 复制代码
public ClassPathXmlApplicationContext(String... configLocations)

xml相对于,基准class的路径

只有这种的会构建configResources

java 复制代码
public ClassPathXmlApplicationContext(String[] paths, Class<?> clazz)
public ClassPathXmlApplicationContext(String path, Class<?> clazz)


String[] configFiles = {
       "innerbeantest.xml"
};
ClassPathXmlApplicationContext cpa = new ClassPathXmlApplicationContext(configFiles, WebConfig.class);

xml配置文件相对于WebConfig类的位置。此时关键还要看构建工具配置,如果XML在java目录下需要额外配置,否则打包不会把java目录下资源文件复制过去

xml 复制代码
<build> 
    <resources> 
        <resource> 
            <directory>src/main/resources</directory> 
            <includes> 
                <include>**/*.xml</include> <!-- 包含XML文件 -->                         </includes> 
        </resource>
        <!-- 如果XML在java目录下需要额外配置 --> 
        <resource> 
            <directory>src/main/java</directory> 
            <includes> <include>**/*.xml</include> 
            </includes> 
        </resource> 
    </resources> 
</build>

加载bean定义时

先加载configResources,再加载configLocations

java 复制代码
protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
    Resource[] configResources = getConfigResources();
    if (configResources != null) {
       reader.loadBeanDefinitions(configResources);
    }
    String[] configLocations = getConfigLocations();
    if (configLocations != null) {
       reader.loadBeanDefinitions(configLocations);
    }
}

我们还是建议直接使用configLocations,除非配置资源专供某一个类,或包使用,为了容易体现他们之间关系,使用configResources。

相关推荐
sql2008help32 分钟前
使用spring-boot-starter-validation实现入参校验
java·开发语言
Mr_Air_Boy36 分钟前
springboot集成xxl-job
java·spring boot·spring
Babybreath-1 小时前
Tomcat
java·tomcat
摇滚侠2 小时前
面试实战 问题二十三 如何判断索引是否生效,什么样的sql会导致索引失效
java
悟纤2 小时前
当生产环境卡成 PPT:Spring Boot 线程 Dump 捉妖指南 - 第544篇
java·spring boot·后端
江影影影3 小时前
Spring Boot 2.6.0+ 循环依赖问题及解决方案
java·spring boot·后端
Jonathan丶BNTang4 小时前
IntelliJ IDEA 2025.2 重磅发布
java·ide·intellij-idea
tanxiaomi5 小时前
学习分库分表的前置知识:高可用系统架构理论与实践
java·mysql·spring cloud·系统架构·springboot
谷哥的小弟5 小时前
Spring Framework源码解析——BeanPostProcessor
spring·源码
m0_741574755 小时前
tomcat
java·tomcat