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

注解说明

    使用注解: @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注解,指定使用的模式,默认是单例模式

示例代码

单例模式示例

在两个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());
    }
}

原型模式示例

在两个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 {
}
经验分享 程序员 微信小程序 职场和发展