控制反转(IOC)、依赖注入(DI)之通过构造函数注入简单属性

来源:互联网 发布:产品跟踪软件 编辑:程序博客网 时间:2024/05/21 10:43

环境配置,如果是idea,直接在建工程的时候勾选spring就可以了,他会帮你自动下载的,如果是eclipse,那就需要导入spring的jar包


我们不讲概念,直接从例子出发。


实体类

/** * Juggler是人 实现了Performer(表演)接口 */public class Juggler implements Performer {    private int balls = 3;    public Juggler() {}    public Juggler(int balls) {        this.balls = balls;    }    @Override    public void perform() throws PerformanceException {        System.out.println("Playing " + balls + " in his hand");    }}
他是一个人,实现了表演的接口里的方法,perform。同时还有一个构造参数,意思就是他手上最多能把玩的球的数量。


接口

public interface Performer {    void perform() throws RuntimeException;}

就很简单的一个人实现了一个表演接口。


接下来就需要配置spring ioc的配置文件了

<beans xmlns="http://www.springframework.org/schema/beans"       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">    <bean id="duck" class="com.example.homework.constructor.Juggler">        <constructor-arg value="15"/>    </bean></beans>

把我们的这个Juggler对象写入进去,并且看一下参数,constructor-arg,显然他是Juggler构造函数传入的值。


所以我们在main里测试一下。

public class JugglerMain {    public static void main(String[] args) {        ApplicationContext ctx = new ClassPathXmlApplicationContext(                "com/example/homework/constructor/spring-juggler.xml"        );        Performer performer = (Performer) ctx.getBean("duck");        System.out.println();        System.out.println();        performer.perform();    }}
首先根据xml的位置取得xml(并且做好了解析工作),因此我们接下来才可以从xml中根据我们个这个对象设置的id-duck来取得它。输出一下。


Playing 15 in his hand


完毕。


我们分析下我们正常应该怎么做的。

Juggler jug = new Juggler(15);


唯一的区别就是原来我们自己是new一个对象,现在是从xml中去取了。好处就在于他解决了对象之间的耦合。可能有人感觉还是一样的。事实上,假如要new一个Juggler这个对象,那么Juggler这个对象必须是存在的!如果它不存在,你这个程序就会报错,就会运行不了。这就是耦合性。而通过xml的方式去取,就是不同的概念了。前者是创建,后者是取。当你要取的时候,框架会为你创建。无疑创建是一种高耦合,取是一种低耦合。这样的做法,大大降低了耦合性。


所有demo jar包 github地址 https://github.com/xubinhong/SpringIocDemo

阅读全文
0 0
原创粉丝点击