最重要的是的是利用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