Spring学习-07:Bean的其他配置

id和name的区别:

id遵守xml约束的id的限制,id约束保证这个属性的值是唯一的,而且必须以字母开始,可以使用字母、数字、连字符、下划线、句话、冒号。

name没有这些要求。

***** 如果bean标签上没有配置id,那么name可以作为id.

***** 开发中Spring和Struts1整合的时候, /login.

<bean name=”/login” class=””>

现在的开发中都使用id属性即可.

类的作用范围scope属性 :

* singleton      :单例的.(默认的值.)

* prototype      :多例的.

* request        :web开发中.创建了一个对象,将这个对象存入request范围,request.setAttribute();

* session        :web开发中.创建了一个对象,将这个对象存入session范围,session.setAttribute();

* globalSession  :一般用于Porlet应用环境.指的是分布式开发.不是porlet环境,globalSession等同于session;

实际开发中主要使用singleton,prototype

编写bean类Customer.java:

package com.helloSpring.demo3;

public class Customer {

}
配置bean:

<bean id="customer" class="com.helloSpring.demo3.Customer"></bean>
编写测试类:

package com.helloSpring.demo3;

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

/**
 * bean的作用范围
 * @author js
 *
 */
public class SpringTest3 {
	@Test
	public void main(){
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
		Customer customer1=(Customer)applicationContext.getBean("customer");
		System.out.println(customer1);
		Customer customer2=(Customer)applicationContext.getBean("customer");
		System.out.println(customer2);
	}
}

发现customer1和customer2是同一个对象:

继续研究:修改Customer.java的代码如下:

package com.helloSpring.demo3;

public class Customer {
	public Customer(){
		super();
		System.out.println("Customer类被实例化了...");
	}
}
运行测试类:

发现,即使获得Customer对象多次,也只实例化一次(即bean配置默认为单例模式)。

下面,修改bean配置为prototype(多例的):

<bean id="customer" class="com.helloSpring.demo3.Customer" scope="prototype"></bean>
运行测试类:

发现实例化两次,customer1和customer2不是同一个对象。




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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值