Bean的作用域

Bean的作用域概述

Bean的作用域就是指Spring中Java Bean 有效范围,其中最为常用的作用域有2种:

  • 单例作用域(singleton):Bean的默认作用域,任何时候获得的Bean对象都是同一个实例
  • 原型作用域(prototype):每次引到bean时都会创建新的实例

可以通过@Scope注解来设置Bean的作用域,该注解可以添加在类前(与@Component注解搭配使用),也可以添加在方法前(与@Bean注解搭配使用)。

Bean的其他类型的作用域如下表所示(了解即可):

Bean的作用域示例

在cn.highedu包下新建SingletonBean:

 
  1. import org.springframework.stereotype.Component;
  2. @Component
  3. public class SingletonBean {
  4. @Override
  5. public String toString() {
  6. return "SingletonBean";
  7. }
  8. }

在cn.highedu.spring包下新建PrototypeBean:

 
  1. import org.springframework.context.annotation.Scope;
  2. import org.springframework.stereotype.Component;
  3. @Component
  4. @Scope("prototype")
  5. public class PrototypeBean {
  6. @Override
  7. public String toString() {
  8. return "PrototypeBean";
  9. }
  10. }

在cn.highedu包下新建ScopeTest类,对Bean的作用域进行测试:

 
  1. import org.springframework.context.ApplicationContext;
  2. import org.springframework.context.annotation.AnnotationConfigApplicationContext;
  3. public class ScopeTest {
  4. public static void main(String[] args) {
  5. ApplicationContext context =
  6. new AnnotationConfigApplicationContext(ContextConfig.class);
  7. // 测试默认的Scope
  8. SingletonBean bean1 = context.getBean(SingletonBean.class);
  9. SingletonBean bean2 = context.getBean(SingletonBean.class);
  10. System.out.println("bean1 和 bean2 是否是同一个对象:" + (bean1 == bean2));
  11. // 测试prototype
  12. PrototypeBean bean3 = context.getBean(PrototypeBean.class);
  13. PrototypeBean bean4 = context.getBean(PrototypeBean.class);
  14. System.out.println("bean3 和 bean4 是否是同一个对象:" + (bean3 == bean4));
  15. }
  16. }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值