刚开始系统的学习Spring,按照其教程试着尝试实例化IOC容器,了解下Spring的基本原理。
实例化Spring IOC容器的简单方法:
(1).方法1:
//如果只有一个spring配置文件也可以直接传递一个string参数,不需要使用数组
ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{“spring配置文件路径”});
(2).方法2:
Resource res = new FileSystemResource(“spring配置文件”);
BeanFactory factory = new XMLBeanFactory(res);
但是在bean-xml的配置文件上遇到了如下的错误:
og4j:WARN No appenders could be found for logger (org.springframework.beans.factory.xml.XmlBeanDefinitionReader).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "main" org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 1 in XML document from file [D:\Myeclipse 9.0\Spring\bean.xml] is invalid; nested exception is org.xml.sax.SAXParseException: cvc-elt.1: Cannot find the declaration of element 'beans'.
提示找不到元素beans 的声明,查找后发现应该是xml文件配置问题
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">
<description>Spring Quick Start</description>
<bean id="TheAction"
class="net.zk.spring.learn.LowerAction">
<property name="message">
<value>HeLLo</value>
</property>
</bean>
</beans>
最终修改配置好一切正常,需要说明的是xmlns对spring版本有严格要求,这里使用的是spring3.0版本。出现问题时,需要按版本自行修改。