IOC容器bean配置文件分析

1、src創建applicationContext.xml文件

bean是在applicationContext.xml文件中編寫,把對象放進bean中。
記住要導入相關springbean的包
在這裏插入圖片描述
在這裏插入圖片描述
創建完成
在這裏插入圖片描述

2、bean標籤分析

  • class:指定bean的全限定名
  • id:bean對象的唯一標記
  • name:bean對象的一個名字,也就是別名,建議創建多個
  • lazy-init:true延遲加載,默認是false

3、bean的生命週期

destroy-method屬性:
當bean從IOC容器銷燬,會觸發此方法
init-method屬性:
當在IOC容器創建,會觸發此方法
(兩個都是方法,寫在對象中,調用bean時就會自動觸發)

public void initCar()
{
System.out.println("User 創建");
}
public void destoryCar()
{
System.out.println("User銷燬");
}

4、實例代碼展示

User對象

public class User {
    private Integer id;
    private String name;
    private String sex;
    private String phone;



    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 getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                ", phone='" + phone + '\'' +
                '}';
    }
}

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="user" name="user1" class="com.gec.bean.User">
        <property name="id">
            <value>1</value>
        </property>
        <property name="name">
            <value>dada</value>
        </property>
        <property name="phone">
            <value>10086</value>
        </property>
        <property name="sex">
            <value>boy</value>
        </property>
    </bean>
</beans>

main實現

import com.gec.bean.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainTest {
    public static void main(String[] args) {
        //獲取IOC容器對象,可以用一個ApplicationContext對象描述此IOC容器對象
        ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");

        //根據配置好的bean中的id獲取bean對象
        User user = (User) ctx.getBean("user");
        System.out.println(user);
    }

}

結果展示
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章