如何理解依赖注入目标是提升组件的重用性。

如何理解依赖注入目标是提升组件的重用性。

首先,依赖注入机制可以在运行期间为组件配置所需资源,而无需在编写组件代码时就加以指定。将原本通过代码为程序提供依赖交给了IOC容器来进行管理,控制权有应用代码转到了外部容器。

public interface PersonDao {
    public void add();
}
 
public class PersonDaoBean1 implements PersonDao {
    public void add(){
         System.out.println("执行PersonDaoBean1里的add()方法");
    }
}
public class PersonDaoBean2 implements PersonDao {
	public void add(){}
    public void delete(){
         System.out.println("执行PersonDaoBean2里的delete()方法");
    }
}
------------------------------------------------------------------------------
public class PersonServiceBean1 implements PersonService {    
    private PersonDao personDao = new PersonDaoBean1();    
        
    public PersonDao getPersonDao() {    
        return personDao;    
    }    
   
    public void setPersonDao(PersonDao personDao) {    
        this.personDao = personDao;    
    }    
        
    public void save(){    
        personDao.add();    
    }    
}  
---------------------------------------------------------------------------------
public class PersonServiceBean2 implements PersonService {    
    private PersonDao personDao = new PersonDaoBean2();    
        
    public PersonDao getPersonDao() {    
        return personDao;    
    }    
   
    public void setPersonDao(PersonDao personDao) {    
        this.personDao = personDao;    
    }    
        
    public void save(){    
        personDao.add();    
    }    
}  

依赖注入的目的:提高组件的重用概率。

如何体现的呢?

举个例子:要创建两个PersonServiceBean对象并使private PersonDao personDao属性引用对象分别为含有不同功能的public interface PersonDao接口实现类,只能通过写两个类PersonServiceBean1类和PersonServiceBean2类来实现,如上图,而通过依赖注入我们只需添加一个xml配置文件(更改property标签即可)而不是再去写一个重复的类,简而言之共用一个PersonServiceBean类注入不同属性值。这就达到了将PersonServiceBean重用的目的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值