Spring Bean作用域簡介

按照spring官網說明,分成如下五種

 

Scope Description

singleton

(Default) Scopes a single bean definition to a single object instance for each Spring IoC container.

prototype

Scopes a single bean definition to any number of object instances.

request

Scopes a single bean definition to the lifecycle of a single HTTP request. That is, each HTTP request has its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.

session

Scopes a single bean definition to the lifecycle of an HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.

application

Scopes a single bean definition to the lifecycle of a ServletContext. Only valid in the context of a web-aware Spring ApplicationContext.

websocket

Scopes a single bean definition to the lifecycle of a WebSocket. Only valid in the context of a web-aware Spring ApplicationContext.

 

 

singleton 單例模式 spring默認容器裏面的一個對象的實例只有一個

舉個栗子:

public class Person {
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    private String name;

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                '}';
    }
}

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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="person" class="demo.guhong.test04.Person" scope="singleton" name="person2">
    <property name="name" value="bitch"/>
</bean>
</beans>

測試:

public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("testbeans.xml");

        Person person = (Person) context.getBean("person");

        Person person2 = (Person) context.getBean("person2");

        System.out.println(person == person2);

    }

----------------------------------------------------

true

Process finished with exit code 0

 

prototype 原型模式:每次從容器中取出來的時候,都是新對象

還是上面的Person,修改xml 中bean屬性:scope

<bean id="person" class="demo.guhong.test04.Person" scope="prototype" name="person2">
    <property name="name" value="bitch"/>
</bean>

結果:

----------------------------------------------------

false

Process finished with exit code 0

 

request sessoion application websocket

都是在web中用到各自對應不同情形的bean存活時間段,後續有機會待補充

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章