sankardev51
sankardev51

Reputation: 37

Retrieving Bean by Name and Type doesnt work - FileNotFoundException

I just started learning Spring and I face the below issue. Could someone highlight what I might be doing wrong?

package org.pus.learn;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringTestApp {
    public static void main(String...args){
        ClassPathXmlApplicationContext test = new ClassPathXmlApplicationContext("applicationBean.xml",Coach.class);
        Coach testCoach = test.getBean("myCoach", Coach.class);
        System.out.println(testCoach.giveAdvice());
    }
}

Exception in thread "main" org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [org/pus/learn/src/main/resources/applicationBean.xml]; nested exception is java.io.FileNotFoundException: class path resource [org/pus/learn/src/main/resources/applicationBean.xml] cannot be opened because it does not exist at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:342)

This is my Project Structure

enter image description here

Upvotes: 0

Views: 66

Answers (1)

Anton Dementyev
Anton Dementyev

Reputation: 68

You start application without initialising the spring context like

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

then in any your Bean-class you can use:

@Autowired // or better use constructor
private ApplicationContext applicationContext;

void yourMethod() {
  applicationContext.getBeansOfType(Coach.class);
}

Upvotes: 0

Related Questions