Spring笔记(二):bean的作用域

在bean中配置作用域使用属性scope来设置bean的作用域

  • scope="singleton" 也是bean配置中默认的配置

    bean配置文件代码:

     
        
        
    
    

    java测试代码:

        ApplicationContext ctx = new ClassPathXmlApplicationContext("bean-scop.xml");
    
        School school = (School) ctx.getBean("school");
        School school1 = (School) ctx.getBean("school");
    
        System.out.println(school);
        System.out.println(school1);     
    

    运行结果:

    School被创建
    Disconnected from the target VM, address: '127.0.0.1:51820', transport: 'socket'
    com.example.demo.entity.School@4d5650ae
    com.example.demo.entity.School@4d5650ae
    
    Process finished with exit code 0
    

    从上可以看出bean属性scope为singleton时,容器初始化时会创建实例,该容器中对象的实例有且只有一个

  • scope="prototype"

    bean配置:

     
        
        
    
    

    java测试代码:

     ApplicationContext ctx = new ClassPathXmlApplicationContext("bean-scop.xml");
    
        School school = (School) ctx.getBean("school1");
        School school1 = (School) ctx.getBean("school1");
    
        System.out.println(school);
        System.out.println(school1);
    
    

    运行结果:

    School被创建
    School被创建
    com.example.demo.entity.School@a38c7fe
    com.example.demo.entity.School@6fdbe764
    

    从运行结果可以看出bean属性scope为prototype时,容器初始化时不会创建bean的实例,只有在调用时才会创建bean的实例;

  • scope="request" 和 scope="session"
    这两个属性都是涉及到与对象,一个是resquest域,两一个是session域

你可能感兴趣的:(Spring笔记(二):bean的作用域)