spring--Scope

 spring  之 Scope

Scope有两个值:singleton(默认)  prototype

                             singleton是单例的

                             prototype是非单例的

   

如:

   Person.java


package
com; public class Person { }
//applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- <bean id="p" class="com.Person" scope="singleton"></bean> --> <bean id="p" class="com.Person" scope="prototype"></bean> </beans>

测试:

package com;

import org.junit.Test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.factory.BeanFactory;

public class TestDemo {

    @Test
    public void test01() {
        //启动spring容器,读取src下applicationContext.xml文件
       ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
       //调用spring容器创建对象
       Person p1 = (Person) ac.getBean("p");
       Person p2 = (Person) ac.getBean("p");
       Person p3 = (Person) ac.getBean("p");
       System.out.println(p1);
       System.out.println(p2);
       System.out.println(p3);
    }
    
    
}

如果scope=“prototype”

结果:

 

 

如果scope=“singleton”

结果:

 

 

 

  

 

 

 

 

 

 

 

 

 

 

 

          

posted @ 2020-03-29 20:31  wwww2  阅读(166)  评论(0编辑  收藏  举报