最重要的是的是利用set方法賦值
首先創建spring項目,引來jar包
其次, xml配置 test創建測試包 創建vo包 創建student、school 並設置構造方法
public class School {
private Student student;
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
}
package com.jd.vo;
public class Student {
}
XML文件:
<?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="stu" class="com.jd.vo.Student"></bean>
<bean class="com.jd.vo.School">
<property name="student" ref="stu"></property>
</bean>
</beans>
再次設置test類:
public class test {
public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext("application.xml");
context.getBean(School.class).getStudent();
}
}
BEAN生命週期
通過構造方法或工廠方法創建bean對象——>爲bean屬性賦值——>調用 bean 的初始化方法,即init-method指定方法——>bean實例化完畢,可以使用——>容器關閉, 調用 bean 的銷燬方法,即destroy-method指定方法。
spring bean生命週期主要分爲初始化創建、使用、銷燬。
注意
在手動啓動關閉容器使用AbstractApplicationContext
代替ApplicationContext
使用close()方法
init-method:在設置bean的屬性後執行的自定義初始化方法,注意:①、該方法不能有參數;②、對象每創建一次就會執行一次該方法;
public class Student {
private String name;
public Student() {
System.out.println("方法");
}
public String getName() {
return name;
}
public void setName(String name) {
System.out.println("setter方法");
this.name = name;
}
public void init() {
System.out.println("初始方法");
}
}
<bean class="com.jd.test.Student" init-method="init">
<property name="name" value="趙地球"></property>
</bean>
ClassPathXmlApplicationContext application = new ClassPathXmlApplicationContext("application.xml");
Student student = application.getBean(Student.class);
System.out.println(student);
application.close();
destroy-method:該參數中的方法只有bean標籤屬性scope爲singleton且關閉Spring IOC容器時纔會被調用,注意:該方法不能有參數
public class Student {
private String name;
public void destroy() {
System.out.println("destroy-method");
}
public void setName(String name) {
this.name=name;
System.out.println(name);
}
public String getName() {
return name;
}
}
<bean class="com.jd.test.Student" destroy-method="destroy" scope="component">
<property name="name" value="趙地球"></property>
</bean>
ClassPathXmlApplicationContext application = new ClassPathXmlApplicationContext("application.xml");
Student student = application.getBean(Student.class);
System.out.println(student);
application.close();
總結:
對象的生命週期:創建(實例化-初始化)-使用-銷燬,而在Spring中,Bean對象週期服從這一過程,但是Spring提供了許多對外接口,允許對三個過程(實例化、初始化、銷燬)的前後做一些操作。
這裏就實例化、初始化區別做一個說明,在Spring Bean中,實例化是爲bean對象開闢空間(具體可以理解爲構造函數的調用),初始化則是對屬性的初始化,這裏的屬性初始化應該是屬性的注入(構造函數也可以有屬性的初始化語句,但不屬於這一部分),屬性注入是通過setter方法注入屬性(不管是註解方式還是bean配置property屬性方式,其實質都是通過屬性的setter方法實現的)。