Spring Bean的Scope

本文详细介绍了Spring框架中Bean的不同作用域,包括Singleton、Prototype、Request、Session和GlobalSession,并通过示例演示了Singleton和Prototype作用域下Bean实例的创建过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一 点睛

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。

二 实战

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

1 编写Singleton的Bean

package com.wisely.highlight_spring4.ch2.scope;

import org.springframework.stereotype.Service;

@Service
//默认为Singleton,相对于@Scope("singleton")
public class DemoSingletonService {

}

2 编写Prototype的Bean

package com.wisely.highlight_spring4.ch2.scope;

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

@Service
@Scope("prototype")//声明Scope为prototype
public class DemoPrototypeService {

}

3 编写配置类

package com.wisely.highlight_spring4.ch2.scope;

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

@Configuration
@ComponentScan("com.wisely.highlight_spring4.ch2.scope")
public class ScopeConfig {

}

4 编写主类

package com.wisely.highlight_spring4.ch2.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("s1与s2是否相等"+p1.equals(p2));
        
        context.close();
    }
}

三 测试

s1与s2是否相等true

s1与s2是否相等false

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值