1.单实例bean
在 Spring 里面,默认情况下,bean 是单实例对象. 单例对象在容器里只有一个.
User类
package com.limi.test;
import org.springframework.beans.factory.FactoryBean;
public class User{
private String name;
public void setName(String name) {
this.name = name;
}
}
测试类
package com.limi.test;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
@Test
public void test1(){
//1.加载bean的xml文件, 以src为根目录
ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
//2.获取配置的对象, 参数1:bean的id值, 参数2: 类名.class
User user1 = context.getBean("User", User.class);
User user2 = context.getBean("User", User.class);
//3.使用对象
System.out.println("user1:"+user1);
System.out.println("\nuser2:"+user2);
}
}
测试结果, 可以看到user1和user2是同一个实例
2.多实例bean
- 多实例bean, 一个类的对象在容器里可以有多个实例.
- 在 spring 配置文件 bean 标签里面有属性(scope)用于设置单实例还是多实例,scope=singleton 对应单实例, scope=prototype对应多实例.
- 设置 scope 值是 singleton 时候,加载 spring 配置文件时候就会创建单实例对象 ,设置 scope 值是prototype 时候,不是在加载 spring 配置文件时候创建对象,在调用 getBean 方法时候创建多实例对象.
<?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">
<!--id是唯一标识, class是全类名 -->
<bean id="User" class="com.limi.test.User" scope="prototype">
<property name="name" value="andy"></property>
</bean>
</beans>
测试结果, 可以看到user1和user2是两个不同的实例