bean的作用域
在spring里面,默认情况下,bean是一个单实例对象
package com.test2;
public class TestA {
private String name;
public void setName(String name) {
this.name = name;
}
}
<?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="testA" class="com.test2.TestA">
<property name="name" value="名字"/>
</bean>
</beans>
package com.test2;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestATest {
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("spring7.xml");
TestA testA = context.getBean("testA", TestA.class);
System.out.println(testA);
TestA testb = context.getBean("testA", TestA.class);
System.out.println(testb);
}
}
com.test2.TestA@43a0cee9
com.test2.TestA@43a0cee9
在spring里面,设置创建bean实例是单例还是多例
在spring配置文件bean标签里面有属性(scope)用于设置单实例还是多实例
scope属性常用值
singleton,默认值,单例的
prototype,多例的
补充两个不是很常用的值
request 一次请求
session 一次会话
<?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="testA" class="com.test2.TestA" scope="prototype">
<property name="name" value="名字"/>
</bean>
</beans>
package com.test2;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestATest {
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("spring7.xml");
TestA testA = context.getBean("testA", TestA.class);
System.out.println(testA);
TestA testb = context.getBean("testA", TestA.class);
System.out.println(testb);
}
}
com.test2.TestA@544a2ea6
com.test2.TestA@2e3fc542
singleton和prototype的区别
singleton单实例,prototype多实例
设置scope值为singleton时,加载spring配置文件的时候就会创建单例对象
设置scope的值为prototype时,它并不是在加载spring配置文件的时候创建对象,而是在调用getBean方法的时候创建多例对象
