天天看點

IOC容器bean配置檔案分析

1、src建立applicationContext.xml檔案

bean是在applicationContext.xml檔案中編寫,把對象放進bean中。

記住要導入相關springbean的包

IOC容器bean配置檔案分析
IOC容器bean配置檔案分析

建立完成

IOC容器bean配置檔案分析

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);
    }

}
           

結果展示

IOC容器bean配置檔案分析