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

Spring的Scope有以下几种,通过@Scope注解来实现。

(1)Singleton:一个Spring容器中只有一个Bean的实例,此为Spring的默认配置,全容器共享一个实例。

(2)Prototype:每次调用新建一个Bean的实例。

(3)Request:Web项目中,给每一个http request新建一个Bean实例。

(4)Session:Web项目中,给每一个http session新建一个Bean实例。

(5)GlobalSession:这个只在portal应用中有用,给每一个global http session新建一个Bean实例。

另外,在Spring Batch中还有一个Scope是使用@StepScope,我们将在批处理一节介绍这个Scope。

本例简单演示默认的singleton和Prototype,分别从Spring容器中获得2次Bean,判断Bean的实例是否相等。

springboot Bean的Scope_Web

 编写Singleton的Bean

SingletonDemo.java

package com.shrimpking;

import org.springframework.stereotype.Service;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Shrimpking
 * @create 2023/6/7 20:58
 */
@Service
public class SingletonDemo
{

}

代码解释

①默认为Singleton,相当于@Scope(“singleton”)。

编写Prototype的Bean

PrototypeDemo.java

package com.shrimpking;

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

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Shrimpking
 * @create 2023/6/7 20:59
 */
@Service
@Scope("prototype")
public class PrototypeDemo
{

}

代码解释

①声明Scope为Prototype。

配置类

ScopeConfig.java

package com.shrimpking;

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

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Shrimpking
 * @create 2023/6/7 21:00
 */
@Configuration
@ComponentScan("com.shrimpking")
public class ScopeConfig
{

}

运行

package com.shrimpking;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

@SpringBootApplication
public class Springboot42BeanscopeApplication
{

    public static void main(String[] args)
    {
        //SpringApplication.run(Springboot42BeanscopeApplication.class, args);
        AnnotationConfigApplicationContext context
                = new AnnotationConfigApplicationContext(ScopeConfig.class);

        SingletonDemo s1 = context.getBean(SingletonDemo.class);
        SingletonDemo s2 = context.getBean(SingletonDemo.class);
        System.out.println("SingletonDemo:s1与s2是否相等" + s1.equals(s2));

        PrototypeDemo p1 = context.getBean(PrototypeDemo.class);
        PrototypeDemo p2 = context.getBean(PrototypeDemo.class);
        System.out.println("PrototypeDemo:p1与p2是否相等" + p1.equals(p2));
        context.close();
    }

}

springboot Bean的Scope_Web_02

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6
标签: Spring