2-2、java详述scope作用

创建Java项目,一个类是Test类 包名com.jd.test,一个类是UserInfo类 包名com.jd.vo,还有一个application.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="UserInfo" class="com.jd.vo.UserInfo" lazy-init="true" scope="prototype">
	</bean>

UserInfo类

package com.jd.vo;

public class UserInfo {

	public UserInfo() {
		System.out.println("构造方法");
	}
}

Test类

package com.jd.test;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {

	public static void main(String[] args) {
		ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext ("application.xml");
		
		Object object = applicationContext.getBean("UserInfo");
		System.out.println(object);
		object = applicationContext.getBean("UserInfo");
		System.out.println(object);
		applicationContext.close();  
	}
}

运行结果:
在这里插入图片描述
解释代码:

scope="prototype"

①prototype 每次调用getBean()方法,获得一个新的对象
②request 用于不同请求
③session 用于不同会话,窗口
④singleton 单例,一个类里创建了对象,在这个类里就一直是这个对象
如果application.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="UserInfo" class="com.jd.vo.UserInfo" lazy-init="true" scope="singleton">
	</bean>

运行结果:
在这里插入图片描述
注意:

scope="singleton"

单例是scope的默认值,如果不在<bean><bean/>里添加scope属性,scope默认的就是一个容器中只能创建这一个对象。
2.22

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值