1.创建两个实现类实现同一个接口
2.更改Spring 配置文件:
<!-- 构造注入 -->
<bean id="iUseAxeImpl" class="com.itstudy.model.impl.IUseAxeImpl">
<constructor-arg ref="stoneAxe"></constructor-arg>
</bean>
<!-- 配置stoneAxe实例,其实现类是StoneAxe -->
<bean id="stoneAxe" class="com.itsutyd.service.impl.StoneAxe"/>
<!-- 配置steelAxe实例,其实现类是SteelAxe -->
<bean id="steelAxe" class="com.itsutyd.service.impl.SteelAxe"/>
3.配置相应的bean:
<!-- 配置useAxe实例,其实现类是 -->
<bean id="iUseAxeImpl" class="com.itstudy.service.impl.IUseAxeImpl">
<!-- 将stoneAxe注入给axe属性 -->
<property name="axe" ref="stoneAxe"/> //id:该bean的唯一标识,程序通过id属性值来访问该Bean实例
</bean>
<!-- 配置stoneAxe实例,其实现类是StoneAxe --> //class:bean的实现类全路径,此处只能用接口的实现类,不可用接口
<bean id="stoneAxe" class="com.itstudy.service.impl.StoneAxe"/>
<!-- 配置steelAxe实例,其实现类是SteelAxe -->
<bean id="steelAxe" class="com.itstudy.service.impl.SteelAxe"/>
4.创建测试类
public class AxeTest {
public static void main(String[] args) {
ApplicationContext ctx = new
ClassPathXmlApplicationContext("bean.xml");
UseAxe ua = (UseAxe)ctx.getBean("iUseAxeImpl");
ua.useingAxe();
}
}