1. 程式人生 > 實用技巧 >3、第一個Spring檔案

3、第一個Spring檔案

1、pojo實體類

/**
 * @author zhangzhixi
 */
public class User {
    private int id;
    private String name;

    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; } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + '}'; } }

2、配置元資料

從spring官網文件上覆制

<?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 https://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- 使用Spring建立物件,在Spring中這些都稱為Bean id:標識單個bean定義的字串 class:完全限定的類名 property:相當於物件中的屬性 name:屬性id value:屬性值 ref:引用spring容器中建立好的物件
--> <bean id="user" class="com.zhixi.pojo.User"> <property name="id" value="2018"/> <property name="name" value="張志喜"/> </bean> </beans>

3、例項化容器

public class MyTest {
    public static void main(String[] args) {
        // 獲取Spring上下文物件,多個xml檔案,用逗號隔開
        ApplicationContext context = new ClassPathXmlApplicationContext("bens.xml");
        // 我們的物件都在spring中進行管理,需要使用的直接去spring容器中取
        User user = (User) context.getBean("user");
        System.out.println(user.toString());

    }
}

User{id=2018, name='張志喜'}