Person 接口
package org.zbq.ioc;
public interface Person {
public void work();
}
Tool 接口
package org.zbq.ioc;
public interface Tool {
public void realWork();
}
Tool 实现类ConcreteToolA
package org.zbq.ioc;
public class ConcreteToolA implements Tool {
@Override
public void realWork() {
System.out.println("Real work from Tool A");
}
}
Tool 实现类ConcreteToolB
package org.zbq.ioc;
public class ConcreteToolB implements Tool {
@Override
public void realWork() {
System.out.println("Real work from Tool B");
}
}
Person实现类 Chinese
package org.zbq.ioc;
public class Chinese implements Person {
private Tool tool;
public Tool getTool() {
return tool;
}
public void setTool(Tool tool) {
this.tool = tool;
}
@Override
public void work() {
tool.realWork();
}
}
applicationContext.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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="toolA" class="org.zbq.ioc.ConcreteToolA"></bean>
<bean id="toolB" class="org.zbq.ioc.ConcreteToolB"></bean>
<bean id="chinese" class="org.zbq.ioc.Chinese">
<property name="tool" ref="toolB"></property>
</bean>
</beans>
Client
package org.zbq.ioc;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
public class Client {
public static void main(String[] args) {
ClassPathResource cpr = new ClassPathResource("applicationContext.xml");
XmlBeanFactory factory = new XmlBeanFactory(cpr);
Person p = (Person)factory.getBean("chinese");
p.work();
}
}