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不是同一个对象。