简体   繁体   中英

Spring can't find bean and throws NoSuchBeanDefinitionException

I have a problem with a realization of Spring in Action example of a programme.

Test class:

@Test
public void testBasicUsage() throws PerformanceException {
    ApplicationContext context = new ClassPathXmlApplicationContext("/**/java/springidol/spring-idol.xml");
    Performer performer = (Performer) context.getBean("juggler");
    performer.perform();
}

Juggler class that should be configured by Spring

public class Juggler implements Performer {

    private int beanBags = 3;

    public Juggler() {
    }

    public Juggler(int beanBags) {
        this.beanBags = beanBags;
    }

    @Override
    public void perform() throws PerformanceException {
        System.out.println("JUGGLING " + beanBags + " BEANBAGS");
    }
}

And xml configuration file for this bean:

<?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 http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="juggler"
          class="springidol.Juggler">
        <constructor-arg value="15"/>
    </bean>
</beans>

this code throw NoSuchBeanDefinitionException:

Aug 30, 2018 1:20:43 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@1c53fd30: startup date [Thu Aug 30 13:20:43 EEST 2018]; root of context hierarchy

org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'juggler' available

    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:686)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1210)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1089)
    at springidol.TestMain.testBasicUsage(TestMain.java:12)

在此处输入图片说明

I think the class-path you provided in ClassPathXmlApplicationContext should be where the XML configuration in present. The files on classpaths are automatically scanned, we just need to provide folder paths. Try below in Test class with changes:

ApplicationContext context = new ClassPathXmlApplicationContext("java/springidol/spring-idol.xml");

Reference: Spring Source

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM