1.singleton
默认情况下,Spring的IoC容器创建的Bean对象是单例的。
public void testFirstSpringCode(){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
Object user1 = applicationContext.getBean("userBean");
System.out.println(user1);
Object user2 = applicationContext.getBean("userBean");
System.out.println(user2);
}
Bean对象的创建是在初始化Spring上下文的时候就完成的。
public class vip {
public vip() {
System.out.println("无参构造方法");
}
}
@Test
public void testVipSpringCode(){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
}
2.prototype
要变成多例则在bean标签中指定scope属性的值为:prototype,这样Spring会在每一次执行getBean()方法的时候创建Bean对象,调用几次则创建几次。这一次初始化Spring上下文的时候,并没有创建Bean对象。
<bean id="userBean" class="com.bean.user" scope="prototype"/>
@Test
public void testFirstSpringCode(){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
Object user1 = applicationContext.getBean("userBean");
System.out.println(user1);
Object user2 = applicationContext.getBean("userBean");
System.out.println(user2);
}
3.其它scope
scope属性的值不止两个,它一共包括8个选项:
- singleton:默认的,单例。
- prototype:原型。每调用一次getBean()方法则获取一个新的Bean对象。或每次注入的时候都是新对象。
- request:一个请求对应一个Bean。仅限于在WEB应用中使用。
- session:一个会话对应一个Bean。仅限于在WEB应用中使用。
- global session:portlet应用中专用的。如果在Servlet的WEB应用中使用global session的话,和session一个效果。(portlet和servlet都是规范。servlet运行在servlet容器中,例如Tomcat。portlet运行在portlet容器中。)
- application:一个应用对应一个Bean。仅限于在WEB应用中使用。
- websocket:一个websocket生命周期对应一个Bean。仅限于在WEB应用中使用。
- 自定义scope:很少使用。
自定义scope:在同一个线程中,获取的Bean都是同一个,跨线程则是不同的对象。
<!--自定义-->
<bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
<property name="scopes">
<map>
<entry key="myThread">
<bean class="org.springframework.context.support.SimpleThreadScope"/>
</entry>
</map>
</property>
</bean>
<!--使用scope-->
<bean id="userBean" class="com.bean.user" scope="myThread"/>
@Test
public void testFirstSpringCode(){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
Object user1 = applicationContext.getBean("userBean");
Object user2 = applicationContext.getBean("userBean");
System.out.println(user1);
System.out.println(user2);
// 启动线程
new Thread(new Runnable() {
@Override
public void run() {
Object a = applicationContext.getBean("userBean");
Object b = applicationContext.getBean("userBean");
System.out.println(a);
System.out.println(b);
}
}).start();
}