scope描述的是spring容器是如何新建bean的实例的。
spring常用的scope有以下几种,通过@scope注解来实现:
为了更好的理解,我们通过具体的代码示例来理解下singleton与prototype的区别。
package scope; import org.springframework.stereotype.service; @service public class demosingletonservice { }
因为spring默认配置的scope是singleton,因此以上代码等价于以下代码:
package scope; import org.springframework.context.annotation.scope; import org.springframework.stereotype.service; @service @scope("singleton") public class demosingletonservice { }
package scope; import org.springframework.context.annotation.scope; import org.springframework.stereotype.service; @service @scope("prototype") public class demoprototypeservice { }
package scope; import org.springframework.context.annotation.componentscan; import org.springframework.context.annotation.configuration; @configuration @componentscan("scope") public class scopeconfig { }
新建一个main类,在main()方法中,分别从spring容器中获取2次bean,然后判断bean的实例是否相等:
package scope; import org.springframework.context.annotation.annotationconfigapplicationcontext; public class main { public static void main(string[] args) { annotationconfigapplicationcontext context = new annotationconfigapplicationcontext(scopeconfig.class); demosingletonservice s1 = context.getbean(demosingletonservice.class); demosingletonservice s2 = context.getbean(demosingletonservice.class); demoprototypeservice p1 = context.getbean(demoprototypeservice.class); demoprototypeservice p2 = context.getbean(demoprototypeservice.class); system.out.println("s1 与 s2 是否相等:" + s1.equals(s2)); system.out.println("p1 与 p2 是否相等:" + p1.equals(p2)); context.close(); } }
运行结果如下:
从运行结果也可以看出,默认情况下即singleton类型的bean,不管调用多少次,只会创建一个实例。
singleton类型的bean,@scope注解的值必须是:singleton。
prototype类型的bean,@scope注解的值必须是:prototype。
即使是大小写不一致也不行,如我们将demoprototypeservice类的代码修改为:
package scope; import org.springframework.context.annotation.scope; import org.springframework.stereotype.service; @service @scope("prototype") public class demoprototypeservice { }
此时运行代码,就会报错:
源码地址:,欢迎下载。
《java ee开发的颠覆者:spring boot实战》
欢迎扫描下方二维码关注公众号:申城异乡人。
如对本文有疑问, 点击进行留言回复!!
before社区电量是什么意思 Before社区电量获得方法
RecycleView入门详解(教你全面掌握RecycleView用法)
动态权限请求框架RxPermissions(几行代码搞定权限)
URL路径@PathVariable出现点号“.“时值遭截断问题
网友评论