5、组件注册-@Scope-设置组件作用域

5、组件注册-@Scope-设置组件作用域

  • IOC容器默认都是单实例的
    /**
     * * {@link ConfigurableBeanFactory#SCOPE_SINGLETON SCOPE_SINGLETON}.
     * * @since 4.2
     * * @see ConfigurableBeanFactory#SCOPE_PROTOTYPE
     * * @see ConfigurableBeanFactory#SCOPE_SINGLETON
     * * @see org.springframework.web.context.WebApplicationContext#SCOPE_REQUEST
     * * @see org.springframework.web.context.WebApplicationContext#SCOPE_SESSION
     * * @see #value
     * <p>
     * <p>
     * prototype 多实例的
     * singleton 单实例的 默认值
     * request 同一个请求创建一个实例(WEB环境)
     * session 同一个session创建一个实例(WEB环境)
     *
     * @return
     */
    @Scope("prototype") // 多实例
    
    
  • prototype 多实例的 IOC容器启动的时候不会创建Bean,每次获取的时候才会去创建Bean
  • singleton 单实例的 默认值 IOC容器启动就会调用方法创建Bean,以后每次就是直接从容器(map.get)中拿
  • request 同一个请求创建一个实例(WEB环境)
  • session 同一个session创建一个实例(WEB环境)
  • 等同于xml
<bean id="pension" class="com.hw.springannotation.beans.Pension" scope="prototype">
        <property name="name" value="hw"></property>
        <property name="age" value="18"></property>
    </bean>
原文地址:https://www.cnblogs.com/Grand-Jon/p/10018647.html