开发工具:
STS(Spring Tool Suite)jar包:
commons-logging-1.1.3.jarspring-beans-4.0.0.RELEASE.jarspring-context-4.0.0.RELEASE.jarspring-core-4.0.0.RELEASE.jarspring-expression-4.0.0.RELEASE.jarStudent.javapackage 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
原文:https://www.cnblogs.com/tukiran/p/15222936.html