首页 文章

springframework.core.io.Resource总是抛出java.io.FileNotFoundException

提问于
浏览
0

我是Spring的初学者,我正在学习资源 .

package com.smart.beanfactory;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

public class BeanLifeCycle {
    private static void LifeCycleInBeanFactory() {
        Resource res = new ClassPathResource("classpath:com/smart/beanfactory/beans.xml");
        try {
            System.out.println(res.getURL());
        } catch (Exception e) {
            System.out.println(e.fillInStackTrace());
        }
    }

    public static void main(String[] args) {
        LifeCycleInBeanFactory();
    }
}

我编写上面的简单代码只是为了使用类路径来加载.xml文件 .

以下是我的项目的层次结构:
enter image description here

然后我尝试了 Resource res = new ClassPathResource("file:/Users/haoxu/Documents/Code/Java/anotherchapter4/src/main/resources/com.smart/beanfactory/beans.xml"); 中的绝对文件路径但是那也行不通 . 它只是告诉我"java.io.FileNotFoundException: class path resource [Users/haoxu/Documents/Code/Java/anotherchapter4/src/main/resources/com.smart/beanfactory/beans.xml] cannot be resolved to URL because it does not exist "

-----------更新--------

我将我的代码修改为:

package com.smart.beanfactory;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import java.io.File;

public class BeanLifeCycle {
    private static void LifeCycleInBeanFactory() {
        Resource res = new ClassPathResource("/com/smart/beanfactory/beans.xml");
        try {
            System.out.println(res.getURL());
        } catch (Exception e) {
            System.out.println(e.fillInStackTrace());
        }
    }

    public static void main(String[] args) {
        LifeCycleInBeanFactory();
    }
}

但我仍然得到“java.io.FileNotFoundException:类路径资源[com / smart / beanfactory / beans.xml]无法解析为URL,因为它不存在”

3 回答

  • 2

    ClassPathResource 不需要前缀 classpath:

  • 0

    尝试下面的代码行

    Resource res = new ClassPathResource("/resources/com/smart/beanfactory/beans.xml");
    
  • 0

    我将文件"beans.xml"复制并粘贴到目录"target/classes/com/smart/beanfactory/" . 层次结构如下
    enter image description here

    我的代码如下:

    package com.smart.beanfactory;
    
    import org.springframework.core.io.ClassPathResource;
    import org.springframework.core.io.Resource;
    
    import java.io.File;
    
    public class BeanLifeCycle {
        private static void LifeCycleInBeanFactory() {
            Resource res = new ClassPathResource("com/smart/beanfactory/beans.xml");
            try {
                System.out.println(res.getURL());
            } catch (Exception e) {
                System.out.println(e.fillInStackTrace());
            }
        }
    
        public static void main(String[] args) {
            LifeCycleInBeanFactory();
        }
    }
    

    结果是“file:/Users/haoxu/Documents/Code/Java/anotherchapter4/target/classes/com/smart/beanfactory/beans.xml”

    这实际上是文件的路径 . 但它位于目标目录中 . 我认为这真的是 strange .

相关问题