再談Spring(一):Bean的作用域

(尊重勞動成果,轉載請註明出處:https://yangwenqiang.blog.csdn.net/article/details/103321567冷血之心的博客)

前言

今天準備開始一個Spring系列文章,主要記錄一些學習和使用Spring過程中遇到的小知識,所以我起了《再談Spring》的名字。


正文

Spring是一個輕量級的IOC和AOP容器框架。是爲Java應用程序提供基礎性服務的一套框架,目的是用於簡化企業應用程序的開發,它使得開發者只需要關心業務需求。

Spring屬於低侵入式設計,代碼的污染極低。並且Spring的控制反轉機制將對象之間的依賴關係交由框架處理,減低組件的耦合性。通過IOC容易來創建一個個的Bean,並且注入到你需要的地方。

今天我們來一起看看Spring Bean的作用域吧,我們使用簡單易上手的SpringBoot來進行介紹。

SpringBoot 是 Spring 開源組織下的子項目,是 Spring 組件一站式解決方案,主要是簡化了使用 Spring 的難度,簡省了繁重的配置,提供了各種啓動器,開發者能快速上手。

接下來,我們一起搭建一個SpringBoot項目吧~

項目目錄如下所示:
在這裏插入圖片描述
啓動類StartApplication如下:

package com.ywq;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * created by yangwenqiang on 2019-11-30
 */

@SpringBootApplication
public class StartApplication {
    // SpringBoot服務的啓動入口
    public static void main(String[] args) {
        SpringApplication.run(StartApplication.class,args);
    }
}

TestController:

package com.ywq.controller;

import com.ywq.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * created by yangwenqiang on 2019-11-30
 */
@RequestMapping("/test")
@RestController
public class TestController {

    @RequestMapping(value = "/scopeTest", method = RequestMethod.GET)
    public String testScope(){

        return "This is Scope Test!";
    }
}

TestService:

package com.ywq.service;

import org.springframework.stereotype.Service;

/**
 * created by yangwenqiang on 2019-11-30
 */

@Service
public class TestService {

    // 下邊可以定義任意的業務處理邏輯
    // ....
}

配置文件application.properties:

server.port=8632

Maven配置文件pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <!--指定parent的starter, 可以省去很多配置-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.1.RELEASE</version>
    </parent>

    <groupId>com.ywq</groupId>
    <artifactId>bean-scope</artifactId>
    <version>1.0-SNAPSHOT</version>

    <!--導入SpringBoot web starter-->
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

    <!--添加SpringBoot的編譯插件-->
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

接下來,我們可以直接運行main方法來啓動項目:
在這裏插入圖片描述
然後打開瀏覽器,效果如下:
在這裏插入圖片描述

好了,這裏我們簡單搭建了一個SpringBoot項目,接下來,我們來對Spring中Bean的作用域做一個簡單的介紹吧~

Spring框架支持以下五種Bean的作用域:

  • singleton : bean在每個Spring IOC 容器中只有一個實例
  • prototype:一個bean的定義可以有多個實例。
  • request:每次http請求都會創建一個bean,該作用域僅在基於web的Spring ApplicationContext情形下有效。
  • session:在一個HTTP Session中,一個bean定義對應一個實例。該作用域僅在基於web的Spring ApplicationContext情形下有效。
  • global-session:在一個全局的HTTP Session中,一個bean定義對應一個實例。該作用域僅在基於web的Spring ApplicationContext情形下有效。缺省的Spring bean 的作用域是Singleton

其中,singleton是Spring默認的Bean作用域,也就是說在當前的IOC容器中只存在一個當前對象。

接下來,我們做一個簡單的驗證:

修改TestController:

package com.ywq.controller;

import com.ywq.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * created by yangwenqiang on 2019-11-30
 */
@RequestMapping("/test")
@RestController
public class TestController {

    @Autowired
    private TestService testService;

    @Autowired
    private TestService testService2;

    @RequestMapping(value = "/scopeTest", method = RequestMethod.GET)
    public String testScope() {
        // 這裏判斷我們注入的TestService的兩個實例對象是否是同一個
        return String.valueOf(testService == testService2);
    }

}

輸出結果如下:
在這裏插入圖片描述
由圖中,可以看到IOC容器給我們注入了兩個TestService的對象實例,但是其實是同一個對象,因爲默認使用了單例。

當我們指定當前要使用多例的時候,可以在定義Bean的時候進行標註,如下所示:

package com.ywq.service;

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

/**
 * created by yangwenqiang on 2019-11-30
 */

@Service
@Scope("prototype")
public class TestService {

    // 下邊可以定義任意的業務處理邏輯
    // ....
}

輸出結果如下:
在這裏插入圖片描述
由圖中可以看出,當前兩次注入的對象實例不是同一個,也就是說在當前IOC容器中存在多個TestService的對象實例。

當我們使用@Scope(“singleton”)進行標註Bean時,會發現結果變爲了true,驗證了默認的作用域確實是singleton。

接下來,我會持續更新在使用Spring過程中使用到的一些小知識點,希望大家可以持續關注~


如果對你有幫助,記得點贊哈,歡迎大家關注我的博客,關注公衆號(文強的技術小屋),學習更多技術知識,一起遨遊知識海洋~

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