第一个Spring程序的撰写,理解SpringIOC工厂机制

搭建Spring开发环境

有关Spring开发环境的搭建,请参考:http://www.moonlightgate.com/archives/79

撰写第一个Spring程序

第一步:在entity包下定义Person实体类。

package com.royotech.entity;

import java.io.Serializable;

public class Person implements Serializable{
    private Integer id;
    private String name;
    private String birthday;
    private String telephone;
    private String address;

    public Person() {
        super();
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getBirthday() {
        return birthday;
    }

    public void setBirthday(String birthday) {
        this.birthday = birthday;
    }

    public String getTelephone() {
        return telephone;
    }

    public void setTelephone(String telephone) {
        this.telephone = telephone;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "Person [id=" + id + ", name=" + name + ", birthday=" + birthday + ", telephone=" + telephone
                + ", address=" + address + "]";
    }
}

备注:

  1. 实体类的创建可以通过Eclipse自动生成代码的方式快速完成。
  2. 实体类为什么要实现Serializable接口,请参考文章:http://www.moonlightgate.com/archives/83

第二步:在applicationContext.xml文件下的<beans>标签下增加以下<bean>标签,内容如下:

<bean id="person" class="com.royotech.entity.Person">
    <property name="id" value="1"></property>
    <property name="name" value="Leon"></property>
    <property name="birthday" value="1990-01-01"></property>
    <property name="telephone" value="13811811118"></property>
    <property name="address" value="北京市西城区"></property>
</bean>   

添加<bean>标签的意思就是希望项目中的某一个类交由Spring框架去管理,由Spring工厂创建对象。
<bean>标签的id属性:对象创建好后,通过这个id取出来使用。
<bean>标签的class属性:交给Spring工厂创建对象的全类名。
<bean>标签的下的<property>标签:类的属性。

**第三步:在view包下创建PersonSpringIOC类

package com.royotech.view;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.royotech.entity.Person;

public class PersonSpringIOC {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); 
        Person p = (Person)ac.getBean("person");  
        System.out.println(p);
    }
}

运行,输出结果如下:
file

理解为什么使用SpringIOC工厂机制创建对象

不得不说,从这个案例来看,创建一个类变得如此复杂,纯属吃饱了撑的,但是我们换个角度去想:

  • 使用SpringIOC创建对象类似于用乐高建房子,房子建好后拆卸仍然很容易。
  • 而使用传统方法创建对象类似用积木和胶水建房子,房子建好了,想拆开可是非常困难的。