@Scope定义bean的作用域

类:
@Component
@Scope("prototype")
public class AnnotationTest {

    private int age;

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public void getName(){
        System.out.println("调用方法");
    }


}
测试:
@RunWith(SpringRunner.class)
@SpringBootTest
public class SprinBootDmeoApplicationTests {

   @Test
   public void contextLoads() {

   }

   @Test
   public void annotation(){
      ApplicationContext ac = new AnnotationConfigApplicationContext(AnnotationTest.class);
      AnnotationTest annotationTest1 = ac.getBean(AnnotationTest.class);
      annotationTest1.setAge(10);
      System.out.println("annotationTest1字节码:"+annotationTest1.hashCode());;
      //每次调用产生一个新的实列
      AnnotationTest annotationTest2 = ac.getBean(AnnotationTest.class);
      annotationTest2.setAge(20);
      System.out.println("annotationTest2字节码:"+annotationTest2.hashCode());;
      System.out.println("实列对象annotationTest1的属性值:"+annotationTest1.getAge());
      System.out.println("实列对象annotationTest1的属性值:"+annotationTest2.getAge());



   }


}

运行结果:

annotationTest1字节码:646204091

annotationTest2字节码:445010547

实列对象annotationTest1的属性值:10

实列对象annotationTest1的属性值:20

总结:

@Scope 定义bean的作用域

默认为singleton,还有prototype,session ,gloal session,required

singleton: 定义该bean是单例模式,在spring容器中,共享一个bean的实列
prototype:每次调用都会创建一个新的bean实列
required:每次请求都会创建一个新的bean实列

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值