当前位置: 首页 > 科技观察

Spring系列:说说@Scope注解的用法,你知道吗?

时间:2023-03-16 12:53:22 科技观察

今天给大家分享一下Spring中@Scope注解的用法,希望对大家有所帮助!一、@Scope定义及作用@Scope注解的主要作用是调整Ioc容器中的作用域。在SpringIoC容器中,主要有以下五个作用域:基本作用域:singleton(单例)、prototype(多例);Web范围(reqeust、session、globalsession)、自定义范围。2.@Scope作用域类型2.1@Scope("singleton")单实例属于默认作用域。IOC容器启动时,会调用创建对象的方法,每次从Spring容器中获取相同的对象(mapamong)。2.2@Scope("prototype")多实例,在IOC容器开始创建的时候,不会直接创建对象放到容器中。当你需要调用时,它会从容器中获取对象,然后创建它。2.3@Scope("request")创建具有相同request的实例2.4@Scope("session")创建具有相同session的实例2.5@Scope("globalsession")创建具有相同globalsession的实例3.示例演示3.1新人。javapackagecom.spring.bean;publicclassPerson{私有字符串名称;私人整数年龄;私有字符串地址;publicPerson(Stringname,Integerage,Stringaddress){this.name=name;这个。年龄=年龄;这。地址=地址;}publicPerson(){}publicStringgetName(){返回姓名;}publicvoidsetName(Stringname){this.name=name;}publicIntegergetAge(){返回年龄;}publicvoidsetAge(Integerage){this.age=age;}publicStringgetAddress(){返回地址;}publicvoidsetAddress(Stringaddress){this.address=address;}@OverridepublicStringtoString(){return"Person{"+"name='"+name+'\''+",age='"+age+'\''+",地址='"+地址+'\''+'}';}}3.2新建配置类TestScopeConfig.javapackagecom.spring.config;importcom.spring.bean.Person;importorg.springframework.beans.factory.config.ConfigurableBeanFactory;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importorg.springframework.context.annotation.Scope;@ConfigurationpublicclassTestScopeConfig{@Bean@Scope("singleton")//@Scope("prototype")publicPersonperson(){System.out.println("容器添加人物对象......");returnnewPerson("小孙",28,"西安");}}3.3新建测试类TestScope.javapackagecom.spring.test;importcom.spring.bean.Person;importcom.spring.config.TestBeanConfig;importcom.spring.config.TestScopeConfig;importorg.springframework.context.annotation.AnnotationConfigApplicationContext;导入org.springframework.context.support.ClassPathXmlApplicationContext;公共类TestScope{publicstaticvoidmain(String[]args){//配置文件方法AnnotationConfigApplicationContextannotationContext=newAnnotationConfigApplicationContext(TestScopeConfig.class);对象person1=annotationContext.getBean("person");对象person2=annotationContext.getBean("person");System.out.println(person1);System.out.println(person2);布尔标志=person1==person2;if(flag){System.out.println("是同一个对象");}else{System.out.println("不是同一个对象");}}}4.输出效果4.1@Scope("prototype")输出结果:容器添加Person对象...Person{name='小孙',age='28',address='西安'}Person{name='小孙',age='28',address='西安'}都是同一个对象4.2@Scope("prototype")output:containeraddedPersonobject...ContaineraddsPersonobject...Person{name='小孙',age='28',address='西安'}人{name='小孙',age='28',address='西安'}不是同一个对象5、@Scope注解的使用场景目前90%以上的业务系统都使用singleton单实例,所以spring默认的类型也是单例,虽然singleton保证了全局是实例,提高了性能,但是如果实例当其中有非静态变量时,可能会造成线程安全、共享资源竞争等问题。当设置为prototypemulti-instance时:每进行一次连接请求,都会重新生成一个新的bean实例,同样会出现问题。当请求数越高,性能越低,因为频繁创建新实例会导致频繁GC,增加GC回收时间。根据实际情况选择哪种方式。