spring学习——scope属性
来源:互联网 发布:鲨鱼记账怎么导出数据 编辑:程序博客网 时间:2024/06/08 12:14
scope属性
scope表示spring容器对一个bean的请求的处理方式,我们常用的设置值有:singleton(默认的)和prototype
singleton
在容器中,从请求bean到容器生命周期结束,有且仅有一个bean的实例,每次请求都返回这个,所以对应生命周期从创建到容器销毁
prototype
每次请求bean,容器都会给生成一个新的实例并返回,返回后容器就不负责这个实例的管理。实例的生命周期就给请求方去管理来。
我们看的简单的例子
配置文件
<?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="helloWorld" class="com.test.Car" scope="singleton"> <property name="brand" value="Spring"/> </bean></beans>
Car类
public class Car { private String brand; private String color; private int maxSpeed; public Car() { } public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public int getMaxSpeed() { return maxSpeed; } public void setMaxSpeed(int maxSpeed) { this.maxSpeed = maxSpeed; }}
调用程序
import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class App { public static void main(String[] args) throws Throwable { ApplicationContext ctx=new ClassPathXmlApplicationContext("file:applicationContext.xml"); Car helloWorld=(Car) ctx.getBean("helloWorld",Car.class); Car helloWorld1=(Car) ctx.getBean("helloWorld",Car.class); System.out.println(helloWorld==helloWorld1); System.out.println(helloWorld.toString()); System.out.println(helloWorld1.toString()); }}
输出
truecom.xxx.Car@49c342bdcom.xxx.Car@49c342bd
两次获取的实例都是同一个,我们把配置文件中的
scope="singleton"
修改成
scope="prototype"
后,输出如下:
falsecom.xxx.Car@5aba9dffcom.xxx.Car@11dafee2
获取实例是不一样的
0 0
- spring学习——scope属性
- 菜鸟学习Struts——Scope属性
- Spring——bean标签的scope属性
- Spring的scope属性
- spring 2.0 scope 属性
- Spring的scope属性
- Spring scope属性详解
- spring bean scope属性
- spring bean属性scope
- Spring的scope属性
- spring中scope属性
- Spring的scope属性
- Spring的scope属性
- Spring scope属性详解
- Spring中scope属性
- Spring scope属性详解
- Spring scope属性详解
- Spring scope属性
- 数组
- HTTP/2:让Web服务更快[翻译]
- PHP接入Protocol Buffer并且实现TCP的二进制流传输
- this关键字
- PHP7革新与性能优化
- spring学习——scope属性
- PHP函数sem_get引起的“No space lelf on device”问题解决记录
- 高并发Web网站构建和安全防护(基础知识分享)
- QQ会员活动运营平台的架构设计演变——高效自动化运营
- QQ会员活动运营平台架构设计实践——高效自动化运营
- android从本地相册获取图片uri三星手机适配问题
- 亿级Web系统的容错性建设实践
- 日请求亿级的QQ会员AMS平台PHP7升级实践
- 应对节日高峰-Web架构实践