011. Spring Bean單例與非單例
阿新 • • 發佈:2019-02-08
1、建立Java專案:File -> New -> Java Project
2、引入必要jar包,專案結構如下
3、建立People實體類People.java
package com.spring.model;
public class People {
private int id;
private String name;
public People() {
super();
System.out.println("Create People");
}
public int getId () {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "People [id=" + id + ", name=" + name + "]";
}
}
4、建立spring配置檔案applicationContext.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="prototypePeople" class="com.spring.model.People" scope="prototype">
<property name="id" value="0"></property>
<property name="name" value="prototypePeople"></property>
</bean>
<!--單例模式,載入applicationContext.xml時初始化物件-->
<bean id="singletonPeople" class="com.spring.model.People" scope="singleton">
<property name="id" value="0"></property>
<property name="name" value="singletonPeople"></property>
</bean>
</beans>
5、建立Spring測試類SpringUnit.java
package com.spring.junit;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringUnit {
ClassPathXmlApplicationContext ctx = null;
@Before
public void setUp() throws Exception {
ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
}
@Test
public void test() {
System.out.println(ctx.getBean("prototypePeople") == ctx.getBean("prototypePeople"));
System.out.println(ctx.getBean("singletonPeople") == ctx.getBean("singletonPeople"));
}
@After
public void tearDown() throws Exception {
ctx.close();
}
}
6、測試結果
... 省略Spring日誌資訊 ...
Create People
Create People
Create People
false
true
... 省略Spring日誌資訊 ...