Spring之路-初识IOC

来源:互联网 发布:linux的syslog开启 编辑:程序博客网 时间:2024/05/24 05:57

Spring是目前主流的框架,使用Spring的目的主要是简化开发。其实,大多数框架的目的都是为了让我们这些码农搬起砖来更高效率,我们首先应明确学习框架的目的,而不应该为了学习框架而去学框架。那么,Spring是怎么简化开发的呢?先来看《Spring实战》中的描述:

为了降低Java开发的复杂性,Spring采取了以下4种关键策略:
基于POJO的轻量级和最小侵入性编程;
通过依赖注入和面向接口实现松耦合;
基于切面和惯例进行声明式编程;
通过切面和模板减少样板式代码。

总的来说,Spring中最重要的内容就是DI(依赖注入)和AOP(面向切面)。下面,我们先聊聊Ioc。
小明是一个苦逼的码农,小红是万恶的产品经理。小红给小明说明需求,小明就开始搬砖,上代码:

//程序员接口public interface Coder {    void coding();}
//产品经理接口public interface ProductManage {    void work();}
//负责A部分的程序员public class CoderA implements Coder {    private String name;    public CoderA(String name){        this.name=name;    }    @Override    public void coding() {        System.out.println("苦逼的码农"+name+"正在搬砖...");    }}
//产品经理Apublic class ProductManageA implements ProductManage {    public ProductManageA(){        Coder xiaoming=new CoderA();    }    @Override    public void work() {        System.out.println("万恶的PM跟码农谈需求");        xiaoming.coding();    }}
//测试方法@Testpublic final void test() {    ProductManage xiaohong=new ProductManageA();    xiaohong.work();}

测试结果:

万恶的PM跟码农谈需求
苦逼的码农xiaoming正在搬砖…

这里,我们不难发现,产品经理与程序员耦合度太高了,小红难道只能让小明打代码吗?显然,应该改进一下:

public class ProductManageA implements ProductManage {    private Coder coder;    public ProductManageA(Coder coder){        this.coder=coder;    }    @Override    public void work() {        System.out.println("万恶的PM跟码农谈需求");        coder.coding();    }}测试方法:
@Testpublic final void test() {    Coder xiaoming=new CoderA("xiaoming");    ProductManage xiaohong=new ProductManageA(xiaoming);    xiaohong.work();}

`
显然结果是一样的,但这样的好处就是耦合度降低了,小红不仅可以安排小明打代码,还可以安排小刚,小李啥的。这是一种代理模式,我们每次都要先new一个程序员,再由把程序员注入产品经理,完成这个工作。显然比较繁琐,而Spring是为了简化开发的,所以我们祭出Spring。在Spring中,就可以使用DI(依赖注入)来完成这个过程,相当于把小明注入,达到控制反转的效果。
首先,我们首先在xml中配置

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xmlns:p="http://www.springframework.org/schema/p"  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">  <bean id="xiaohong" class="program.ProductManageA">    <constructor-arg ref="xiaoming" />  </bean>  <bean id="xiaoming" class="program.CoderA">      <constructor-arg value="xiaoming" />  </bean></beans>

然后,测试此次输出

    @Test    public final void test() {        FileSystemXmlApplicationContext context=                new FileSystemXmlApplicationContext("磁盘中位置/ProductManageA.xml");        ProductManageA pmA=context.getBean(ProductManageA.class);        pmA.work();        context.close();    }

“`

万恶的PM跟码农谈需求
苦逼的码农xiaoming正在搬砖…

完美输出。我们可以发现,Spring帮助我们构造了程序员,简化了编程。

原创粉丝点击