Spring入门_IOC控制反转.docx

  1. 1、本文档共5页,可阅读全部内容。
  2. 2、有哪些信誉好的足球投注网站(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。
  3. 3、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载
  4. 4、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
Spring入门_IOC控制反转

====================Demo==========================publicclass PersonService {private String name;privateintage;publicvoid setAge(int age) {this.age = age;}publicvoid info() {System.out.println(姓名: + name+ 年龄:+age);}publicvoid setName(String name) {this.name = name;}}=====================Config========================== = = = = beanname=personclass=com.dao.PersonServicepropertyname=namevalue=杨飞/propertypropertyname=agevalue=12/property/bean= = = = = = = = = = = = = = = = = = = = = Test= = = = = = = = = = = = = = = = = = = = = = = = = = = = = =ApplicationContext content = newClassPathXmlApplicationContext(applicationContext.xml);PersonService ps = content.getBean(person, PersonService.class);ps.info();姓名:杨飞年龄:12= = = = = = = = = = = = = = = = = = = = = End= = = = = = = = = = = = = = = = = = = = = = = = = = = = = 上面两行代码并不是直接创建Person实例,而是通过Spring容器获取Person实例的,这正式Spring容器的作用,Spring容器不仅可以创建Person实例,而且该Person的name属性和age属性有了属性值。Spring容器根据配置文件信息,负责创建Person实例,并为Person实例设置属性值-----------这种由Spring容器设置属性的方式被称为控制反转(IOC)控制反转/依赖注入,依赖注入是目前最优秀的解耦方式,依赖注入让Spring的Bean以配置文件组织在一起,而不是以硬编码的方式耦合在一起。依赖注入通常有两种方式:设置注入:IOC容器使用属性Setter方法来注入被依赖的实例构造注入:IOC容器使用构造器来注入被依赖的实例= = = = = = = = = = = = = = = = = = = = Demo Dao= = = = = = = = = = = == = = = = = = = = = = == =publicinterface Person {// 定义了一个使用斧子的方法publicvoid useAxe();}publicinterface Axe {//有一个坎的方法public String chop();}= = = = = = = = = = = = = = = = = = = = Dao Impl= = = = = = = = = = = = = = = = = = = = = = = = =publicclassStoneAxeimplements Axe {public String chop() {return石斧砍柴好慢;}}publicclass Chinese implementsPerson {// 人使用斧子,那么必须有一个斧子private Axe axe;publicvoid setAxe(Axe axe) {this.axe = axe;}publicvoiduseAxe() {System.out.println(axe.chop());}}到现在为止Chinese还不知道和那个Axe实例耦合,Spring当然也不知道!!Spring需要使用XMl配置文件来指定实例之间的依赖关系。= = = = = = = = = = = = = = = = = = = = =Config= = = = = = = = = = = = = = = = = = = = = = = = = = = = = =beanid=chineseclass=com.dao.impl.Chinesepropertyname=axeref=stoneAxe/property/beanbeanid=stoneAxeclass=com.dao.impl.Ston

文档评论(0)

yan698698 + 关注
实名认证
内容提供者

该用户很懒,什么也没介绍

1亿VIP精品文档

相关文档