经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 其他 » 职业生涯 » 查看文章
SpringIOC的小例子
来源:cnblogs  作者:bihang  时间:2018/11/16 10:10:55  对本文有异议

IOC

IOC--Inversion of Control即控制反转,常常和DI--依赖注入一起被提到。

核心是为了解除程序之间的耦合度。

那么什么样的代码是耦合度高的呢?

假如有个人现在去买苹果

  1. interface Fruit{}
  2. class Apple implements Fruit{}
  3. class Person{
  4. private Apple apple;
  5. public Person(){
  6. apple = new Apple();
  7. }
  8. }

然后家里有苹果了,又去买梨子,这时候就得改代码

  1. class Pear implements Fruit{}
  2. class Person{
  3. private Pear pear;
  4. public Person(){
  5. pear = new Pear();
  6. }
  7. }

再买别的就得一直改代码。
假如把代码解耦,只留下接口,写成这样

  1. class Person{
  2. public Fruit fruit;
  3. public Person(Fruit fruit){
  4. this.fruit = fruit;
  5. }
  6. }

可以看到Person构造器没有自行创建要买的水果,而是将水果这个接口作为参数传递进来,我们称这种方式为构造器注入

假如现在再买橘子,只需要创建橘子类和修改Spring的配置文件就可以,不用修改Person类的代码。

  1. class Orange implements Fruit{}
  2. <bean id="orange" class="cn.bh.springtest.Orange" />
  3. <bean id="person" class="cn.bh.springtest.Person">
  4. <constructor-arg ref="orange">
  5. </bean>

在测试类里面测试

  1. ApplicationContext applicationContext =new ClassPathXmlApplicationContext("spring.xml");
  2. Person person = (Person) applicationContext.getBean("person");
  3. System.out.println(person.fruit.toString());//输出cn.bh.springtest.Orange@6895a785

可以看到没有改动代码的情况下买到了橘子。

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号