1. 程式人生 > >Spring單例和多例

Spring單例和多例

使用bean的scope屬性來控制單例和多例:

    <!-- bean 的 scope屬性可以控制單例和多例
        singleton是預設值:單例的 ;
        prototype:   多例的;
        request:  在web應用中每次請求重新例項化;
        session:  在web應用中每次會話重新例項化;
     -->
    <bean id="people" class="com.spring.pojo.People" scope="singleton"></bean>
    <
bean id="people2" class="com.spring.pojo.People" scope="prototype"></bean>

 

測試程式碼:

public class Test {
    public static void main(String[] args) {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
//        String[] beans = applicationContext.getBeanDefinitionNames();
// System.out.println(Arrays.toString(beans)); People people1 = applicationContext.getBean("people",People.class); People people2 = applicationContext.getBean("people",People.class); System.out.println(people1==people2); People people3 = applicationContext.getBean("people2",People.class
); People people4 = applicationContext.getBean("people2",People.class); System.out.println(people3==people4); } }

控制檯輸出:

true
false

單例設計模式,懶漢式: 由於加了鎖,所以效率低,於是產生了餓漢式

//單例設計模式:懶漢式
public class Teacher {
    private static Teacher teacher;
    private Teacher() {}
    public static Teacher getInstance() {
        if(teacher==null) {
            //考考慮到多執行緒,雙重判斷
            synchronized(Teacher.class) {
                if(teacher==null) {
                    teacher=new Teacher();
                }
            }
        }
        return teacher;
    }
}

單例設計模式,餓漢式:

//單例設計模式:餓漢式
public class Teacher {
    //在物件例項化裡就賦值
    private static Teacher teacher = new Teacher();
    private Teacher() {}
    public static Teacher getInstance() {
        return teacher;
    }
}