bean的作用域解析
说明
意义
1.在Spring中,Bean的作用域可以通过scope属性来指定。
2.指定作用域的目的是 存储在此类单例bean的高速缓存中,并且对该命名bean的所有后续请求和引用都返回该高速缓存的对象。(本身的理念就是以空间换时间的思维,创建步骤繁杂,而且频繁用到,我就存起来,下次用的时候就不用了创建了)
3.了解了目的之后,自然也就有了多种类型,大多数会使用singleton,当然也会有希望每次用到的就是新产生的故而出现prototype类型,还有就是某些范围经常用到,另一些范围不经常用到的,衍生了request和session的范围性质的单例
类型与范围
常见的有:
1)singleton:代表单例的,也是默认值(singleton存储在三级缓存内,本质上是容器applicationcontext里面的三级缓存)
2)prototype:代表多例的(prototype不会对bean进行存储,而是在每次需要的时候进行创建)
3)request:代表范围性质的单例(request存储在对应的请求构建的请求对象里面setAttribute)
4)session:代表范围性质的单例(session存储在对应的请求构建的请求对象里面setAttribute)
5)application:application则是作用域整个应用里面多个applicationcontext共享
6)包括自定义作用域
代码展示
// mbd 指的是前面部分的 final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); if (mbd.isSingleton()) { sharedInstance = getSingleton(beanName, () -> { try { return createBean(beanName, mbd, args); } catch (BeansException ex) { destroySingleton(beanName); throw ex; } }); bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd); } else if (mbd.isPrototype()) { // It"s a prototype -> create a new instance. Object prototypeInstance = null; try { beforePrototypeCreation(beanName); prototypeInstance = createBean(beanName, mbd, args); } finally { afterPrototypeCreation(beanName); } bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd); } else { String scopeName = mbd.getScope(); // 这一步获取的就是存储单例的缓存,针对不同类型获取不同的缓存块【如request对应的RequestScope,session对应的SessionScope】 final Scope scope = this.scopes.get(scopeName); if (scope == null) { throw new IllegalStateException("No Scope registered for scope name "" + scopeName + """); } try { //类似于getSingleton的方式,在缓存中拿不到才会走工厂方法获取 Object scopedInstance = scope.get(beanName, () -> { beforePrototypeCreation(beanName); try { return createBean(beanName, mbd, args); } finally { afterPrototypeCreation(beanName); } }); bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd); } catch (IllegalStateException ex) { throw new BeanCreationException(beanName, "Scope "" + scopeName + "" is not active for the current thread; consider " + "defining a scoped proxy for this bean if you intend to refer to it from a singleton", ex); } }