Spring入門(五):Spring Bean Scope講解

1. 前情回顧

Spring入門(一):建立Spring項目html

Spring入門(二):自動化裝配beanjava

Spring入門(三):經過JavaConfig裝配beangit

Spring入門(四):使用Maven管理Spring項目github

2. 什麼是Bean的Scope?

Scope描述的是Spring容器是如何新建Bean的實例的。spring

Spring經常使用的Scope有如下幾種,經過@Scope註解來實現:session

  1. Singleton:一個Spring容器中只有一個Bean的實例,即全容器共享一個實例,這是Spring的默認配置。
  2. ProtoType:每次調用新建一個Bean的實例。
  3. Request:Web項目中,給每個http request新建一個Bean實例。
  4. Session:Web項目中,給每個http session新建一個Bean實例。

3. 示例

爲了更好的理解,咱們經過具體的代碼示例來理解下Singleton與ProtoType的區別。測試

3.1 新建Singleton類型的Bean

package scope;

import org.springframework.stereotype.Service;

@Service
public class DemoSingletonService {
}

由於Spring默認配置的Scope是Singleton,所以以上代碼等價於如下代碼:prototype

package scope;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

@Service
@Scope("singleton")
public class DemoSingletonService {
}

3.2 新建ProtoType類型的Bean

package scope;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

@Service
@Scope("prototype")
public class DemoPrototypeService {
}

3.3 新建配置類

package scope;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan("scope")
public class ScopeConfig {
}

3.4 測試

新建一個Main類,在main()方法中,分別從Spring容器中獲取2次Bean,而後判斷Bean的實例是否相等:3d

package scope;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ScopeConfig.class);

        DemoSingletonService s1 = context.getBean(DemoSingletonService.class);
        DemoSingletonService s2 = context.getBean(DemoSingletonService.class);

        DemoPrototypeService p1 = context.getBean(DemoPrototypeService.class);
        DemoPrototypeService p2 = context.getBean(DemoPrototypeService.class);

        System.out.println("s1 與 s2 是否相等:" + s1.equals(s2));
        System.out.println("p1 與 p2 是否相等:" + p1.equals(p2));

        context.close();
    }
}

運行結果以下:code

從運行結果也能夠看出,默認狀況下即Singleton類型的Bean,無論調用多少次,只會建立一個實例。

4. 注意事項

Singleton類型的Bean,@Scope註解的值必須是:singleton。

ProtoType類型的Bean,@Scope註解的值必須是:prototype。

即便是大小寫不一致也不行,如咱們將DemoPrototypeService類的代碼修改成:

package scope;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

@Service
@Scope("PROTOTYPE")
public class DemoPrototypeService {
}

此時運行代碼,就會報錯:

5. 源碼

源碼地址:https://github.com/zwwhnly/spring-action.git,歡迎下載。

6. 參考

《Java EE開發的顛覆者:Spring Boot實戰》

歡迎掃描下方二維碼關注公衆號:申城異鄉人。

相關文章
相關標籤/搜索