最重要的是的是利用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方法实现的)。