参差荇菜,左右流之
©Zi10ng
今天第一次学习spring,在配置bean.xml的时候花了好多时间
ApplicationContext常用的有三个实现类,分别是
1. ApplicationContext ap = new ClassPathXmlApplicationContext("String location") 加载类路径下的配置文件,要求配置文件必须在类路径下
2. ApplicationContext ap = new FileSystemXmlApplicationContext("") 加载本地磁盘的配置文件
3. ApplicationContext ap = new AnnotationConfigApplicationContext() 读取注解创建容器
问题描述
- 我的文件目录是这样的

- XML是最简单的配置
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="accountService" class="service.impl.AccountServiceImpl"></bean>
<bean id="accountDao" class="dao.impl.AccountDaoImpl"></bean>
</beans>
当我在test中写出如下代码的时候:
// 获取Spring容器
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
//根据id获得Bean对象
AccountService accountService = (AccountService) applicationContext.getBean("accountService");
会产生如下异常

但是一个悲伤的消息来了!当我博客写到这里,再次去运行程序的时候,竟然又跑通了!!!Spring真是门玄学!
当我只要在service中代码写成这样子的时候:
private ApplicationContext ac = new FileSystemXmlApplicationContext("src/main/resources/bean.xml");
private AccountDao accountDao = ac.getBean("accountDao",AccountDao.class);
或者这样子:
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
private AccountDao accountDao = ac.getBean("accountDao",AccountDao.class);
无论test中写入什么,会产生如下异常:
7月 09, 2019 5:24:19 下午 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@4461c7e3: startup date [Tue Jul 09 17:24:19 CST 2019]; root of context hierarchy
7月 09, 2019 5:24:19 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [bean.xml]
以上四条信息会无限循环!(PS:路径肯定没错)
问题原因
我看了N遍,程序的逻辑没有问题。不会出现互相嵌套的情况
没找出来
解决办法
没找出来
博主首次学习Spring,在配置bean.xml时耗时久。介绍了常用的三个实现类,描述了在test和service中写代码时出现的异常情况,虽多次检查程序逻辑没问题,但未找出问题原因和解决办法,最后感慨Spring像玄学。
7204

被折叠的 条评论
为什么被折叠?



