<?xml version="1.0" encoding="UTF-8"?>
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
c:age="29" c:axe-ref="stoneAxe"/>
package com.app.service;
public interface Person {
public void useAxe();
}
package com.app.service;
public interface Axe {
public String chop();
}
package com.app.service.impl;
import com.app.service.Axe;
public class StoneAxe implements Axe {
public String chop() {
return "石斧头砍柴好慢";
}
}
package com.app.service.impl;
import com.app.service.Axe;
public class SteelAxe implements Axe{
public String chop() {
return "钢斧头真快";
}
}
package com.app.service.impl;
import com.app.service.Axe;
import com.app.service.Person;
public class Chinese implements Person {
private Axe axe;
private int age;
public Chinese(Axe axe,int age){
this.axe = axe;
this.age = age;
}
public void useAxe() {
System.out.println(axe.chop());
System.out.println("age成员变量的值:" + age);
}
}
package com.app.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.app.service.Person;
public class SpringTest {
public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext("beans.xml");
Person p = ctx.getBean("chinese",Person.class);
p.useAxe();
}
}
运行测试类报错如下:
log4j:WARN No appenders could be found for logger (org.springframework.core.env.StandardEnvironment).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'chinese' is defined
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:641)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1157)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:280)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:198)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:979)
at com.app.test.SpringTest.main(SpringTest.java:11)