zoukankan      html  css  js  c++  java
  • Spring入门---Spring Bean的作用域【第一天】

    一、Spring Bean的作用域:

    Spring2.0之前Bean只有两种作用域,即单例【singleton】和non-singleton(也成prototype)Spring2.0之后,增加了sessionrequestglobal session这三种专用于Web运用程序上下文的BeanSpring2.0之后对Bean的类型进行了重构,并设计出灵活的Bean支持,理论上可以有无数多种类型的Bean。可根据需要增加新的Bean类型,以满足实际运用的需求。

    (后续可学习如何重构新的Bean类型)

    1、singleton单实例:

    当一个bean的作用域设置为singleton,那么Spring IOC容器只会存在一个共享的Bean实例,并且所有对Bean的请求只要ID与该Bean定义相匹配,则只会返回Bean的同一实例。即该实例会存储在缓存中。

    配置:

    <bean id=”userdao” class=”test2.dao.UserDao” scope=”singleton”/>

    或者:

    <bean  id=”userdao” class=”test2.dao.UserDao” scope=”true”>

    UserDao bean1 = (UserDao)factory.getBean(“userdao”);

    UserDao bean2 = (UserDao)factory.getBean(“userdao”);

    bean1bean2的引用相同,每次使用getBean()不会重新产生一个实例。

    2、prototype多实例:

    每个容器中,一个Bean对应多个实例。prototype作用域部署的Bean,每一次请求(将其注入到另一个Bean中,或者以程序的方式调用Spring容器的getBean方法)都会产生一个新的Bean实例。

    配置:

    <bean id=”userdao” class=”test2.dao.UserDao” scope=”prototype”/>

    或者:

    <bean  id=”userdao” class=”test2.dao.UserDao” scope=”false”>

    UserDao bean1 = (UserDao)factory.getBean(“userdao”);

    UserDao bean2 = (UserDao)factory.getBean(“userdao”);

    3、request:

    request表示该针对每一次HTTP请求都会产生一个新的Bean,同时该Bean仅在当前HTTP request内有效。

    <bean id=”userdao” class=”test2.dao.UserDao” scope=”request”/>

    4、session:

    session的作用域表示该针对每一次HTTP请求都会产生一个新的Bean,同时该Bean仅在当前HTTP session内有效。

    <bean id=”userdao” class=”test2.dao.UserDao” scope=”session”/>

  • 相关阅读:
    horizontal line and right way to code it in html, css
    Inline vs. block-level elements: a demonstration
    How wide is the default `<body>` margin?
    Getting wrong Version from Assembly using Reflection
    Where is the default size of a div element defined or calculated?
    Why padding is included in height sometimes?
    动态分析Android App之动态调试
    学习: Linux的 date 命令
    一个有趣的安全分析场景DSL设计
    Beats Elastic中的Auditbeat使用介绍
  • 原文地址:https://www.cnblogs.com/ciscolee/p/10931910.html
Copyright © 2011-2022 走看看