org.springframework.beans.factory.nosuchbeandefinitionexception

z4bn682m  于 2021-07-04  发布在  Java
关注(0)|答案(1)|浏览(486)

我从spring开始,在使用基于xml的bean工厂运行这个spring应用程序时,它给出了 NoSuchBeanDefinitionException -

Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'myCoach' available
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:816)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1288)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:207)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1115)
at com.paras.springdemo.HelloSpringApp.main(HelloSpringApp.java:14)

类-hellospringapp.java

package com.paras.springdemo;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class HelloSpringApp {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath*:applicationContext.xml");
        Coach theCoach = context.getBean("myCoach", Coach.class);
        System.out.println(theCoach.getDailyWorkout());
        context.close();
    }
}

应用程序上下文.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
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd">

    <bean id="myCoach"
        class="com.paras.springdemo.TrackCoach">            
    </bean>
</beans>

接口-coach.java

package com.paras.springdemo;

public interface Coach {
    public String getDailyWorkout();
}

trackcoach.java文件

package com.paras.springdemo;
public class TrackCoach implements Coach {

    @Override
    public String getDailyWorkout() {
        return "run 5k";
    }

}
r1zhe5dt

r1zhe5dt1#

xml中缺少这一行

<context:component-scan base-package="com.paras" />

和改变

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

ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

只需确保您的xml位于src/applicationcontext.xml中

相关问题