Spring Annotation(二)

在使用注释配置之前,先来回顾一下传统上是如何配置 Bean 并完成 Bean 之间依赖关系的建立。下面是 3 个类,它们分别是 Office、Car 和 Boss,这 3 个类需要在 Spring 容器中配置为 Bean:

Office 仅有一个属性:


清单 1. Office.java

package com.baobaotao; public class Office { 
    private String officeNo =”001”; 
    
    //省略 get/setter 

    @Override 
    public String toString() { 
        return "officeNo:" + officeNo; 
    } 
}

 

Car 拥有两个属性:


清单 2. Car.java

package com.baobaotao; public class Car { 
    private String brand; 
    private double price; 

    // 省略 get/setter 

    @Override 
    public String toString() { 
        return "brand:" + brand + "," + "price:" + price; 
    } 
}

 

Boss 拥有 Office 和 Car 类型的两个属性:


清单 3. Boss.java

package com.baobaotao; public class Boss { 
    private Car car; 
    private Office office; 
    
    // 省略 get/setter 

    @Override 
    public String toString() { 
        return "car:" + car + "\n" + "office:" + office; 
    } 
}

 

我们在 Spring 容器中将 Office 和 Car 声明为 Bean,并注入到 Boss Bean 中:下面是使用传统 XML 完成这个工作的配置文件 beans.xml:


清单 4. beans.xml 将以上三个类配置成 Bean

<?xml version="1.0" encoding="UTF-8" ?> 
<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-2.5.xsd"> 

    <bean id="boss" class="com.baobaotao.Boss"> 
        <property name="car" ref="car"/> 
        <property name="office" ref="office" /> 
    </bean> 

    <bean id="office" class="com.baobaotao.Office"> 
        <property name="officeNo" value="002"/> 
    </bean> 

    <bean id="car" class="com.baobaotao.Car" scope="singleton"> 
        <property name="brand" value=" 红旗 CA72"/> 
        <property name="price" value="2000"/> 
    </bean> 

</beans>

 

当我们运行以下代码时,控制台将正确打出 boss 的信息:


清单 5. 测试类:AnnoIoCTest.java


import org.springframework.context.ApplicationContext; 
import org.springframework.context.support.ClassPathXmlApplicationContext; 

public class AnnoIoCTest { 
    public static void main(String[] args) { 
        String[] locations = {"beans.xml"}; 
        ApplicationContext ctx = new ClassPathXmlApplicationContext(locations); 
        Boss boss = (Boss) ctx.getBean("boss"); 
        System.out.println(boss); 
    } 
}
posted @ 2012-11-29 19:52  小余儿123  阅读(215)  评论(0编辑  收藏  举报