
I’m learning spring dependency injection. I have 2 types of code. One works and one doesn’t… But, they both work for the person who made the tutorial.
The commented code gives me the error shown below.
@SuppressWarnings("deprecation")
public static void main(String[] args) {
//ApplicationContext factory = new ClassPathXmlApplicationContext("Beans.xml");
//The code below works
BeanFactory factory = new XmlBeanFactory(new FileSystemResource("Beans.xml"));
HelloWorld obj = (HelloWorld) factory.getBean("helloworld");
obj.getMessage();
}
Beans.xml
<?xml version="1.0"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xsi:schemaLocation="
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
">
<bean id="helloworld" class="com.vulab.hellow.HelloWorld">
<property name="message" value="Hello World" />
</bean>
</beans>
Error message when I use ApplicationContext
Exception in thread “main” org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [Beans.xml]; nested exception is java.io.FileNotFoundException: class path resource [Beans.xml] cannot be opened because it does not exist
For
XmlBeanFactoryto work,Beans.xmlwould have to be in the same directory as the calling class.An easy alternative is make sure that
Beans.xmlis located in your classpath. You could copy them intosrc\resourcesand then use:ClassPathXmlApplicationContextis more convenient as absolute file locations do not need to be specified.Note: As of Spring 3.1
XmlBeanFactoryis a deprecated which means that an alternative such as this should be used should you change from 3.0.