您的位置:首页 > 编程语言 > Java开发

Spring管理的bean的作用域

2017-04-20 00:16 253 查看
我们在实例化bean的时候就会有一个疑惑,通过getBean方法得到的bean对象是同一个bean对象,还是不同的bean对象。下面具体讨论bean的作用域。

1,默认情况下的作用域

<?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-2.5.xsd"> <bean id="personService" class="yanxi.service.implement.PersonServiceBean"></bean>
</beans>


springTest.java

package junit.test;

import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import yanxi.service.PersonService;

public class SpringTest {

@BeforeClass
public static void setUpBeforeClass() throws Exception {
}

@Test public void instanceSpring(){
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
PersonService personService1 = (PersonService)ctx.getBean("personService");
PersonService personService2 = (PersonService)ctx.getBean("personService");
System.out.println(personService1==personService2);
}
}


输出结果为 true

根据输出结果显示,在默认情况下,spring实例化bean得到的都是同一个对象,即bean的作用域是在spring容器中。

2,scope=”singleton”

更改配置文件bean的scope属性

<?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-2.5.xsd"> <bean id="personService" class="yanxi.service.implement.PersonServiceBean" scope="singleton"></bean>
</beans>


输出结果为 true

根据输出结果显示,在scope=”singleton”下,spring实例化bean得到的都是同一个对象,即bean的作用域是在spring容器中。

3,scope=”prototype”

更改配置文件bean的scope属性

<?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-2.5.xsd"> <bean id="personService" class="yanxi.service.implement.PersonServiceBean" scope="prototype"></bean>
</beans>


输出结果为 false

根据输出结果显示,在scope=”prototype”下,spring实例化bean得到的不是同一个对象。

第一种第二种情况下,都体现了spring使用了单例模式的特点
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  spring bean