Search code examples
javaandroidspringjavabeans

Error in fetching beans from xml file in spring


I am new to spring. I created config.xml in which I created beans. When I tried to use getBean, I was getting the following error:

IOException parsing XML document from class path resource [config.xml]; nested exception is java.io.FileNotFoundException: class path resource [config.xml] cannot be opened because it does not exist.

I was using this line earlier.

ApplicationContext context= new ClassPathXmlApplicationContext(" config.xml");

Student Student1=(Student) context.getBean("s1");

Then, I changed the code to this:

ApplicationContext context= new ClassPathXmlApplicationContext("classpath*: config.xml");

But, now i am getting new error: No bean named 's1' available

My main function is present in src/main/java/org/example/App.java

My config.xml is present in src/main/java/config.xml

Content of config.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"
   xmlns:context="http://www.springframework.org/schema/context"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="s1" class="org.example.Student"> <!--org.example is groupId-->
    <property name="studentId">
        <value>22344</value>
    </property>
    <property name="studentName">
        <value>AP</value>
    </property>
    <property name="studentAddress">
        <value>L</value>
    </property>
</bean>

Solution

  • You must put the xml file config.xml into src/main/resources (by default maven look for you Java source files into src/main/java and for your resource files into src/main/resources)

    You don't need the classpath keyword when creating the ClassPathXmlApplicationContext object, juste use ClassPathXmlApplicationContext("config.xml") like below :

    ApplicationContext context= new ClassPathXmlApplicationContext("config.xml");
    Student student1=(Student) context.getBean("s1");
    System.out.println(student1.getStudentId());