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。

相关推荐
狼爷6 小时前
吃透 Java Function 接口,搞定 99% 的 Stream 场景
java·函数式编程
祎雪双十Gy10 小时前
从 DataX 的配置加载说起:我用 FastJson2 做了一个轻量级动态配置管理库
java·后端
小锋java123410 小时前
分享一套锋哥原创的SpringBoot4+Vue3宠物领养网站系统
java
考虑考虑14 小时前
Java实现hmacsha1加密算法
java·后端·java ee
掉鱼的猫14 小时前
Spring Boot → Solon 注解迁移实战指南:一张对照表说清楚
java·spring boot
plainGeekDev14 小时前
广播接收器 → Flow + Lifecycle
android·java·kotlin
plainGeekDev14 小时前
EventBus → SharedFlow
android·java·kotlin
带刺的坐椅15 小时前
Spring Boot → Solon 注解迁移实战指南:一张对照表说清楚
java·springboot·web·solon
用户37215742613515 小时前
Java 将一个 PPT 文档拆分为多个文件
java
人活一口气1 天前
Spring Boot与AIGC的完美结合:从零搭建智能内容生成平台
java·spring boot·aigc