如何理解依赖注入目标是提升组件的重用性。
首先,依赖注入机制可以在运行期间为组件配置所需资源,而无需在编写组件代码时就加以指定。将原本通过代码为程序提供依赖交给了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重用的目的。