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

示例代码

完整参考代码github

单例模式示例

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

1
2
3
4
5
6
7
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component
@Scope
public class MyScope {
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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());
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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不是同一个。

1
2
3
4
5
6
7
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

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

运行结果