1. 程式人生 > >第三講:3.1 spring 如何裝配bean

第三講:3.1 spring 如何裝配bean

1,複製專案Spring402 ,改名為Spring402-02。建包:com.cruise.entity .建類:People類,定義屬性 id name age,get()和 set()方法,package com.cruise.entity;public class People {     private int id;     private String name;     private int age;          public int getId() {        return id;     }     public void setId(int id) {        this

.id = id;     }     public String getName() {        return name;     }     public void setName(String name) {        this.name = name;     }     public int getAge() {        return age;     }     public void setAge(int age) {        this.age = age;     } }2,在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.xsd"> <bean id="people" class="com.cruise.entity.People"
></bean>    </beans>3. 刪除沒用的包:com.cruise.service包,刪除沒有的類:在com.cruise.test包下,只要一個test2類即可,其他的類都刪除掉。3.1_spring_裝配bean4. 修改com.cruise.test包下Test2類,執行-測試package com.cruise.test;import org.springframework.context.support.ClassPathXmlApplicationContext;import com.cruise.entity.People;public class Test2 {     public static void main(String[] args) {        ClassPathXmlApplicationContext CA = newClassPathXmlApplicationContext("beans.xml");        People people = (People)CA.getBean("people");//people與beans.xml中的id一致        System.out.println(people);     } }