Spring中bean的生命周期

0.开发环境

开发工具:

  • STS(Spring Tool Suite)

jar包:

  • commons-logging-1.1.3.jar
  • spring-beans-4.0.0.RELEASE.jar
  • spring-context-4.0.0.RELEASE.jar
  • spring-core-4.0.0.RELEASE.jar
  • spring-expression-4.0.0.RELEASE.jar
bean的作用域
  • Singleton 单例
  • Prototype 多例
  • Request 在一次请求中有效
  • Session 在一此会话中有效
单例
测试bean: Student.java
package com.moon.ioc.scope;

public class Student {
	private Integer sid;
	private String sname;
	public Integer getSid() {
		return sid;
	}
	public void setSid(Integer sid) {
		this.sid = sid;
	}
	public String getSname() {
		return sname;
	}
	public void setSname(String sname) {
		this.sname = sname;
	}
	public Student() {
		super();
		// TODO Auto-generated constructor stub
	}
	/*@Override
	public String toString() {
		return "Student [sid=" + sid + ", sname=" + sname + "]";
	}*/
	
}

配置文件scope.xml,bean的属性scope设置为singleton


<?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="student" class="com.moon.ioc.scope.Student" scope="singleton">
		<property name="sid" value="1001"></property>
		<property name="sname" value="王朝" ></property>
	</bean>
</beans>

测试代码:Test.java

package com.moon.ioc.scope;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {
	public static void main(String[] args) {
		ApplicationContext ac = new ClassPathXmlApplicationContext("scope.xml");
		Student student1 = ac.getBean("student", Student.class);
		Student student2 = ac.getBean("student", Student.class);
		System.out.println(student1);
		System.out.println(student2);
	}
}

运行结果:

创建两个Student实例,内存地址是一样的

信息: Loading XML bean definitions from class path resource [scope.xml]
com.moon.ioc.scope.Student@402a079c
com.moon.ioc.scope.Student@402a079c

Spring中bean的生命周期

上一篇:Java程序的种类


下一篇:LeetCode——面试题 17.14. 最小K个数(Java)