zoukankan      html  css  js  c++  java
  • 二、配置你的bean

    一、bean有五种作用域

    <bean scope="singleton" >
    在每个spring IOC容器中一个bean仅有一个实例
    <bean scope="prototype" >
    一个bean定义对应多个实例
    <bean scope="request" >
    在一次http请求中,一个bean对应一个实例
    
    
    <bean scope="session" >
    在一个httpsession中一个bean对应一个实例
    
    
    <bean scope="global-session" >
    在一个全局httpsession中,一个bean对应一个实例


    在不配置scope的情况下,默认scope="singleton"

    当applicationContext.xml是

    <bean id="user" class="com.beans.User">
            <property name="name" value="蔡文姬"/>
        </bean>

    或者

    <bean id="user" class="com.beans.User" scope="singleton">
            <property name="name" value="蔡文姬"/>
        </bean>

    运行下列代码

    package com.test;
    
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    import com.beans.User;
    
    public class Test {
        
        public static void main(String[] args) {
            ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
            User user1=(User) ac.getBean("user");
            User user2=(User) ac.getBean("user");
            System.out.println(user1+" "+user2);
        }
    }


    打出com.beans.User@1af33d6 com.beans.User@1af33d6,说明两个user是同一个对象

    同理测试scope="prototype"得到两个user的地址不同,说明两个user是两个不同的对象

  • 相关阅读:
    牛客(14)链表中倒数第k个结点
    牛客(13)调整数组顺序使奇数位于偶数前面
    牛客(12)数值的整数次方
    牛客(11)二进制中1的个数
    牛客(10)矩形覆盖
    牛客(9)变态跳台阶
    牛客(8)跳台阶
    牛客(7)斐波那契数列
    Docker数据卷
    Docker镜像
  • 原文地址:https://www.cnblogs.com/myz666/p/8098211.html
Copyright © 2011-2022 走看看