Spring学习(4) - Bean的管理

1. Bean的管理者

  • BeanFactory:

    是Spring里面最低层的接口,提供了最简单的容器的功能,只提供了实例化对象和拿对象的功能;

  • ApplicationContext:
    应用上下文,继承BeanFactory接口,它是Spring的一各更高级的容器,提供了更多的有用的功能;
    1) 国际化(MessageSource)
    2) 访问资源,如URL和文件(ResourceLoader)
    3) 载入多个(有继承关系)上下文 ,使得每一个上下文都专注于一个特定的层次,比如应用的web层
    4) 消息发送、响应机制(ApplicationEventPublisher)
    5) AOP(拦截器)

谈一点字词粗俗的理解:
ApplicationContext,字面上的意思,就是应用环境。也比BeanFactory更加具体。而定义应用环境里面有哪些东西,可以分别通过XML,File,WebXml来定义。配置文件,就会定义,在IoC容器中,需要的资源放在了哪里,存放哪些Bean,Bean将如何被管理,Bean与Bean之间的关系,依赖注入,如何切面。

两者装载bean的区别
1. BeanFactory:
启动的时候不会去实例化Bean,中有从容器中拿Bean的时候才会去实例化;
2. ApplicationContext:
在启动的时候就把所有的Bean全部实例化了(默认情况下);
它还可以为Bean配置lazy-init=true来让Bean延迟实例化。

延迟实例化的优点:
应用启动的时候占用资源很少;对资源要求较高的应用,比较有优势;

不延迟实例化的优点:
1. 所有的Bean在启动的时候都加载,系统运行的速度快;
2. 在启动的时候所有的Bean都加载了,我们就能在系统启动的时候,尽早的发现系统中的配置问题

官方文档中的说明:
用BeanFactory都是为了兼容以前的第三方插件。用到的一些接口BeanFactoryAware, InitializingBean, DisposableBean。BeanFactory提供了Spring的IoC功能的底层基础,但它只是直接用于与其他第三方框架的集成。

ApplicationContext继承BeanFactory接口,包含了BeanFactory的所有功能。建议都是用ApplicationContext。除非是运行在资源限制内存消耗管理比较严格的设备上。


2. Bean的作用域
对我来说,一开始很难理解“域”这个词。我觉得还是理解英文的scope比较来得直接。明白了所表达的意思,是最好的。作用域(scope)是Bean在IoC容器里存在的时长,将会定义Bean何时被创建,何种情况下被创建,何时又会被容器放弃管理。

spring中,定义了如下几种Scope

ScopeDescription
singleton(Default) Scopes a single bean definition to a single object instance per Spring IoC container.
prototypeScopes a single bean definition to any number of object instances.
requestScopes a single bean definition to the lifecycle of a single HTTP request; that is, each HTTP request has its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.
sessionScopes a single bean definition to the lifecycle of an HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.
applicationScopes a single bean definition to the lifecycle of a ServletContext. Only valid in the context of a web-aware Spring ApplicationContext.
websocketScopes a single bean definition to the lifecycle of a WebSocket. Only valid in the context of a web-aware Spring ApplicationContext.

全盘照搬就没意思了,这里是:Spring中Bean的scope解释,有兴趣的可以看看。

精简一点的内容:
1. Spring的Singleton和GoF中的单例模式是有区别的。
 GoF中的singleton是 per Classloader per bean
 Spring中singleton是 per Container per bean
2. 要注意单例的Bean依赖非单例的Bean的情况
  因为Singleton只初始化一次,所以如果要替换当中的依赖,就必须使用方法注入依赖(Method-inject)。
3. request, session, application, websocket 这几个域只能在Web应用中使用
  可以借助ApplicationContext 的实现(比如 XmlWebApplicationContext)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值