spring接口实现类 依赖注入

Java code 
 
public Interface MobileInterface{
     public boolean dialUp(long number);
 }
 

Person类: 
 
Java code 
 
public class Person{
     private MobileInterface mobileInterface;
     public boolean makeCall(long number){
         return this.mobileInterface.dialUp(number);
     }
     public void setMobileInterface(MobileInterface mobileInterface){
         this.mobileInterface=mobileInterface;
     }
 }
 在xml文件中配置依赖关系 
 
Java code 
 <bean id="person" class="Person">
     <property name="mobileInterface">
         <ref local="mobileInterface"/>
     </property>    
 </bean>
 <bean id="mobileInterface" class="Mobile"/>
 这样,Person类在实现拨打电话的时候,并不知道Mobile类的存在,它只知道调用一个接口MobileInterface,而MobileInterface的具体实现是通过Mobile类完成,并在使用时由容器自动注入。
 ---------------------------------以上是复制过来的代码
 
Person类中有这个方法----mobileInterface.dialUp(number)。mobileInterface是个接口,怎么可以直接调用该接口实现类的方法?还有其怎么依赖注入的?请大侠拔刀相助啊,急...... 


第一个问题:百度下“java 向上转型” 接口为父类 ,赋值的为子类,用父类调用,其实相当于还是调用子类的方法。
第二个问题:通过java反射机制,获取到person的属性,同时根据配置文件中所配置的依赖类实例化给person的属性。


不使用反射的话,代码应该是这样的

private MobileInterface mobileInterface = new Mobile();
反射相当于帮你实现了new Mobile(); 原理是用java反射实现的 
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值