我从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";
}
}
1条答案
按热度按时间r1zhe5dt1#
xml中缺少这一行
和改变
到
只需确保您的xml位于src/applicationcontext.xml中