控制反转(IOC)和依赖注入(DI)
在普通的编码中,如果一个类A依赖于另一个类B,那么为了实现相应功能,则需要使用new关键字,在这个A类中new类B的一个实例对象出来,这就导致了,类B的生命周期完全由类A来进行控制,并且带来较高的耦合度,如果A的功能需要改动,那么必须修改B的业务逻辑 ,假如A类还被其他类所依赖,那么可能会带来打地鼠一样的问题。为了使得代码间的耦合度降低,则将类的控制权转移到第三方,也就是交给spring容器管理,也就是IOC。那么为了维护类之间的依赖关系,则需要进行依赖注入。
package cn.itcast.service.impl;public class PersonDaoBean {public void add(){System.out.println("我是add方法,用于测试依赖注入");}
}package cn.itcast.service.impl;public class PersonServiceBean implements PersonService {/* (non-Javadoc)* @see cn.itcast.service.impl.PersonService#save()*/private PersonDaoBean personDao;PersonServiceBean(){System.out.println("实例化 ");}public PersonDaoBean getPersonDao(){return personDao;}public void setPersonDao(PersonDaoBean personDao){this.personDao=personDao;}public void init(){System.out.println("初始化");}public void destory(){System.out.println("关闭资源");}public void save(){System.out.println("我是save方法");personDao.add();}
}//在PersonServiceBean类中的save()方法中需要调用PersonDaoBean类中的add()方法,此时不需要在PersonServiceBean类中直接new出一个PersonDaoBean对象,而是在该类中建立PersonDaoBean属性以及建立set和get方法,并且在。spring配置文件中配置PersonDaoBean类和PersonServiceBean类,并且通过 给PersonServiceBean中的personDao属性
赋值即可,此时通过这样的配置可以将PersonDaoBean对象注入进去
package springTest;import static org.junit.Assert.*;import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;import cn.itcast.service.impl.PersonService;public class SpringTest {@Testpublic void test() {AbstractApplicationContext context =new ClassPathXmlApplicationContext("beans.xml");PersonService ps1=(PersonService) context.getBean("personService");//PersonService ps2=(PersonService) context.getBean("personService");context.close();//System.out.println(ps1==ps2);ps1.save();}}










