我是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文件 .
以下是我的项目的层次结构:
然后我尝试了 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 回答
ClassPathResource
不需要前缀classpath:
尝试下面的代码行
我将文件"beans.xml"复制并粘贴到目录"target/classes/com/smart/beanfactory/" . 层次结构如下
我的代码如下:
结果是“file:/Users/haoxu/Documents/Code/Java/anotherchapter4/target/classes/com/smart/beanfactory/beans.xml”
这实际上是文件的路径 . 但它位于目标目录中 . 我认为这真的是 strange .