SpringBoot中的Bean作用域————@scope

17 篇文章 0 订阅
11 篇文章 0 订阅

注解说明

  • 使用注解: @scope
  • 效果:指定Bean的作用域 ,默认的是singleton,常用的还有prototype

Scope的全部可选项

  1. singleton 全局只有一个实例,即单例模式
  2. prototype 每次注入Bean都是一个新的实例
  3. request 每次HTTP请求都会产生新的Bean
  4. session 每次HTTP请求都会产生新的Bean,该Bean在仅在当前session内有效
  5. global session 每次HTTP请求都会产生新的Bean,该Bean在 当前global Session(基于portlet的web应用中)内有效

引入步骤

在类上加入@Scope注解,指定使用的模式,默认是单例模式

示例代码

完整参考代码github

单例模式示例

在两个MysScopeTest中都注入MyScope,测试结果可以发现两个MyScopeTest中的MyScope是同一个。

package com.markey.com.markey.annotations.Scope;

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

@Component
@Scope
public class MyScope {
}
package com.markey.com.markey.annotations.Scope;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;

@Component
public class MyScopeTest1 {

    @Autowired
    MyScope myScope;

    @PostConstruct
    public void sayMyScope() {
        System.out.println("hello,i am MyScopeTest1, my scope is " + myScope.toString());
    }
}
package com.markey.com.markey.annotations.Scope;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;

@Component
public class MyScopeTest2 {

    @Autowired
    MyScope myScope;

    @PostConstruct
    public void sayMyScope() {
        System.out.println("hello,i am MyScopeTest2, my scope is " + myScope.toString());
    }
}

相同Bean

原型模式示例

在两个MysScopeTest中都注入MyScope,测试结果可以发现两个MyScopeTest中的MyScope不是同一个。

package com.markey.com.markey.annotations.Scope;

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

@Component
@Scope("prototype")
public class MyScope {
}

不同Bean

  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值