1:和变量一样,bean也有作用域,spring中我们可以为bean指定作用域:<bean id="" class="" scope="....">
2:作用域的种类
singleton:单例模式,在spring中只有一个实例,无论多少个Bean引用,始终都会指向同一个对象。这也是spring默认的作用域。
prototype:原型模式,spring容器会为每一个引用创建一个新实例。
request:每一个HTTP请求都会创建一个新的bean,但仅仅在当前的request中有效。
session:每一个HTTP Session都会创建一个新的bean,但仅仅在当前HTTP Session中有效。
global Session:在一个全局的HTTP Session中,容器会创建实例,但仅仅在当前范围有效。
实际开发中,单例和原型用的比较多。
3:演示单例模式作用域
bean定义
- public class TopicService
- {
- public void addTopic()
- {
- System.out.println("add topic");
- }
- }
xml配置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:
- http:
-
- <!-- 生产任意内容 -->
- <bean id="topServiceID" class="com.canyugan.scope.TopicService"></bean>
-
- </beans>
测试单例模式下是否引用的是同一个实例:
- @Test
- public void demo1()
- {
- String xmlpath="com/canyugan/scope/beans.xml";
- ApplicationContext applicationContext=new ClassPathXmlApplicationContext(xmlpath);
-
- TopicService topicService1=applicationContext.getBean("topServiceID",TopicService.class);
- System.out.println(topicService1);
- TopicService topicService2=applicationContext.getBean("topServiceID",TopicService.class);
- System.out.println(topicService2);
- }