欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2024-03-24 16:41:46
...

1.Bean的作用域

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

2.常用的作用域

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

3.例子

3.1新建一个空的spring项目

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

3.2创建java文件

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

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运行结果

aaa@qq.com
aaa@qq.com
aaa@qq.com
aaa@qq.com

4.总结

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