Scope,也称作用域,在 Spring IoC 容器是指其创建的 Bean 对象相对于其他 Bean 对象的请求可见范围。在 Spring IoC 容器中具有以下几种作用域:基本作用域(singleton、prototype),Web 作用域(reqeust、session、globalsession),自定义作用域。

  1. singleton: 一个spring容器只有一个bean的实例,此为spring的默认配置
  2. prototype: 每次通过getBean方法取得的prototype都会新建一个bean实例
  3. request: 给每个http request新建一个bean实例
  4. session: 给每个http session新建一个bean实例
  5. GlobalSession: 这个只在portal应用中用,给每个global http session新建一个bean实例

下面就是通过代码解释基本作用域singleton与prototype的区别

创建SingletonService类:

package com.example.testdemo.service;

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

@Service
//@Scope(value = "singleton") spring默认
public class SingletonService {
}

创建PrototypeService类:

package com.example.testdemo.service;

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

@Service
@Scope(value = "prototype")
public class PrototypeService {
}

创建ScopeConfig类

package com.example.testdemo.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;

@Component
@ComponentScan("com.example.testdemo.service")
public class ScopeConfig {
}

创建启动类:

package com.example.testdemo;

import com.example.testdemo.config.ScopeConfig;
import com.example.testdemo.service.PrototypeService;
import com.example.testdemo.service.SingletonService;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;


public class TestdemoApplication {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context=new AnnotationConfigApplicationContext(ScopeConfig.class);
        SingletonService a1=context.getBean(SingletonService.class);
        SingletonService a2=context.getBean(SingletonService.class);
        PrototypeService b1=context.getBean(PrototypeService.class);
        PrototypeService b2=context.getBean(PrototypeService.class);
        System.out.println("a1是否等于a2:"+a1.equals(a2));
        System.out.println("b1是否等于b2:"+b1.equals(b2));
    }
}

运行结果为:

从而验证了singleton与prototype的区别

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐