1. 程式人生 > >Spring系列之三:SpringBean的單例構造和多例構造(Maven Idea)

Spring系列之三:SpringBean的單例構造和多例構造(Maven Idea)

在使用Spring的Ioc容器建立物件會使用到單例構造或多例構造;

單例構造:整個程式只有一個物件

多例構造:程式中有類例項的多個物件,物件之間互相獨立

首先在Test包下面建立一個User類,原始碼如下;

package com.lydetails.ssm.Test;
public class User {
    private String name;
    private Integer age;
    public User() {
        System.out.println("User建構函式");
}

    public String getName() {
        return 
name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }

然後在配置檔案中配置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="user" class="com.lydetails.ssm.Test.User" scope="singleton"></bean>
</beans>

然後在測試類中進行測試:

package com.lydetails.ssm.Test;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class DemoTest {
   @Test //測試使用ioc容器的空參構造
public void func1() {
        //載入配置檔案
ApplicationContext apl = new ClassPathXmlApplicationContext("ApplicationContext.xml");
User introduceDemo = (User) apl.getBean("user");
System.out.println(introduceDemo);
}

    @Test
//測試單例程式碼
public void func2() {
        //載入配置檔案
ApplicationContext apl = new ClassPathXmlApplicationContext("ApplicationContext.xml");
User user1 = (User) apl.getBean("user");
User user2 = (User) apl.getBean("user");
User user3 = (User) apl.getBean("user");
System.out.println(user1==user3);
}
}

輸出的結果如下:


接下來我們來構造多例模式:

其配置原始檔如下所示,只是scrop的值發生改變

<?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="user" class="com.lydetails.ssm.Test.User" scope="prototype"></bean>
</beans>

下面給出測試的原始碼fun3

@Test
//測試多例程式碼
public void func3() {
    //載入配置檔案
ApplicationContext apl = new ClassPathXmlApplicationContext("ApplicationContext.xml");
User user1 = (User) apl.getBean("user");
User user2 = (User) apl.getBean("user");
User user3 = (User) apl.getBean("user");
System.out.println(user2==user3);
}

結果如下所示:

產生了三個建構函式