spring Bean的作用域--单例&原型

20 篇文章 1 订阅

1.Bean的作用域

1.单例-singleton
2.原型-prototype
3.request
4.session
5.globalSession
6.websocket

2.常用的作用域

单例和原型是通用的作用域,其余的在网络编程中能够用到。

3.例子

3.1新建一个空的spring项目

在这里插入图片描述

3.2创建java文件

在这里插入图片描述

package bean;

public class Bean {

	public void say(){
		System.out.println(this);
	}
	
}

package client;

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

import bean.Bean;

public class Main {

	public static void main(String[] args) {

		String path = "resource/beans-";
		@SuppressWarnings("resource")
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
				path + "singleton.xml");
		Bean bean = (Bean)applicationContext.getBean("bean");
		bean.say();
		bean = (Bean)applicationContext.getBean("bean");
		bean.say();
		applicationContext = new ClassPathXmlApplicationContext(path
				+ "prototype.xml");
		bean = (Bean)applicationContext.getBean("beanp");
		bean.say();
		bean = (Bean)applicationContext.getBean("beanp");
		bean.say();
	}

}

3.3xml文件

beans-prototype.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="beanp" class="bean.Bean" scope="prototype">
	</bean>
</beans>

beans-singleton.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="bean" class="bean.Bean" scope="singleton">
	</bean>
</beans>

3.4运行结果

bean.Bean@ae45eb6
bean.Bean@ae45eb6
bean.Bean@6a4f787b
bean.Bean@685cb137

4.总结

spring的Bean的作用域
1.Singleton
2.Prototype

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值