一开始是想尝试一下spring在过去的xml文件配置bean 的感觉,但是在测试
FileSystemXmlApplicationContext
的时候,反复确认文件路径没有问题,将/ -> \\
也不起作用,后决定debug一下,发现根因。记录一下,方便springboot 的新人参考。(声明,开发我不会使用到这个方式创建 bean)
文章目录
- 测试代码
- 运行结果
- debug
- 解决方案
测试代码
package com.example.show_bean;import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;public class ApplicationContextTest {public static void main(String[] args) {testFileSystemXmlApplicationContext();}/*** 基于磁盘路径的 xml 配置文件来创建*/private static void testFileSystemXmlApplicationContext() {FileSystemXmlApplicationContext context = new FileSystemXmlApplicationContext("/Users/xx/project/java/easy_spring_mvc/learn_spring/show_bean/src/test/resources/b01.xml");System.out.println(context.getBean(Bean2.class).getBean1());}/*** java 配置类来创建*/private static void testAnnotationConfigApplicationContext() {}public static class Bean1 {Bean1() {System.out.println(">>>>>>>>>> 1");}}public static class Bean2 {private Bean1 bean1;public Bean2() {System.out.println(">>>>>>>>>>>> 2.");}public void setBean1(Bean1 bean1) {this.bean1 = bean1;}public Bean1 getBean1() {return bean1;}}}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"><bean id="bean1" class="com.example.show_bean.ApplicationContextTest.Bean1"/><bean id="bean2" class="com.example.show_bean.ApplicationContextTest.Bean2"><property name="bean1" ref="bean1"/></bean></beans>
文件🌲
运行结果
Exception in thread “main” org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from file [/Users/xx/project/java/easy_spring_mvc/learn_spring/Users/csjerry/project/java/easy_spring_mvc/learn_spring/show_bean/src/test/resources/b01.xml]; nested exception is java.io.FileNotFoundException: Users/xx/project/java/easy_spring_mvc/learn_spring/show_bean/src/test/resources/b01.xml
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:342)
at com.example.show_bean.ApplicationContextTest.main(ApplicationContextTest.java:10)
Caused by: java.io.FileNotFoundException: Users/csjerry/project/java/easy_spring_mvc/learn_spring/show_bean/src/test/resources/b01.xml
at org.springframework.core.io.FileSystemResource.getInputStream(FileSystemResource.java:189)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:333)
debug
原因
在 FileSystemXmlApplicationContext 中传入路径,如果是'/'
开头会被截掉一个,导致路径不全。
解决方案
简单粗暴多加一个 /