我对程序的Spring in Action示例的实现有疑问。
测试类:
@Test
public void testBasicUsage() throws PerformanceException {
ApplicationContext context = new ClassPathXmlApplicationContext("/**/java/springidol/spring-idol.xml");
Performer performer = (Performer) context.getBean("juggler");
performer.perform();
}
应该由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");
}
}
此bean的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"
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>
此代码抛出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)
答案 0 :(得分:0)
我认为您在ClassPathXmlApplicationContext
中提供的类路径应该是当前XML配置所在的位置。类路径上的文件会自动扫描,我们只需要提供文件夹路径即可。
尝试在Test类中进行以下更改:
ApplicationContext context = new ClassPathXmlApplicationContext("java/springidol/spring-idol.xml");