Spring 一二事(4) - 单例

简介: spring bean配置后再默认情况下是单例的,如果需要配置可以选择 prototype, request, session和global session 在配置spring mvc的action时,可以对action使用 prototype 1    2 4 5 6 bean的创建销毁过程: 1 package com.

 

spring bean配置后再默认情况下是单例的,如果需要配置可以选择 prototype, request, session和global session

在配置spring mvc的action时,可以对action使用 prototype

1    <!-- singleton: 默认单例 prototype: 多例 request ,session和global session: 只适用于web程序 -->
2     <bean id="scope_prototype" class="com.lee.spring005.scope.Scope"
3         scope="prototype"></bean>
4 
5     <!-- destroy-method 一般在数据源的时候用到,关闭容易后就销毁连接 -->
6     <bean id="initDestory" class="com.lee.spring006.init_destory.InitDestory"
7         init-method="init" destroy-method="destory"></bean>

bean的创建销毁过程:

 1 package com.lee.spring006.init_destory;
 2 
 3 public class InitDestory {
 4 
 5     public InitDestory() {
 6         System.out.println("InitDestory() ");
 7     }
 8 
 9     public void hello() {
10         System.out.println("Hello InitDestory!");
11     }
12     
13     public void init() {
14         System.out.println("init");
15     }
16     
17     public void destory() {
18         System.out.println("destory");
19     }
20 }

测试:

 1     @Test
 2     public void testInitDestory() {
 3 
 4         ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
 5         
 6         InitDestory initDestory = (InitDestory)context.getBean("initDestory");
 7         initDestory.hello();
 8         
 9         ClassPathXmlApplicationContext app = (ClassPathXmlApplicationContext)context;
10         app.close();
11     }

 github地址:https://github.com/leechenxiang/maven-spring001-helloworld

相关文章
|
XML Java 数据格式
Spring系列(三)之Bean的生命周期以及Bean的单例与多例模式
Spring系列(三)之Bean的生命周期以及Bean的单例与多例模式
|
缓存 算法 安全
Spring 为啥默认把bean设计成单例的?这篇讲的明明白白的
Spring 为啥默认把bean设计成单例的?这篇讲的明明白白的
389 0
|
XML Java 数据格式
【Spring】Bean的生命周期与单例实现(二)
【Spring】Bean的生命周期与单例实现(二)
304 1
|
XML Java 数据格式
【Spring】Bean的生命周期与单例实现(一)
【Spring】Bean的生命周期与单例实现
292 1
|
XML Java 数据格式
Spring之bean单例与多例
Spring之bean单例与多例
556 0
|
XML 安全 Java
Spring框架中的单例bean是线程安全的吗?阿里一面
在 Spring 框架中,Bean 是指由 Spring IoC(Inversion of Control)容器管理的组件或对象。Bean 是 Spring 中最基本的构建块,它们由 Spring 容器实例化、组装和管理。
456 0
|
安全 Java Spring
Spring框架中的单例Bean是线程安全的吗?
Spring框架中的单例Bean是线程安全的吗?
455 1
|
设计模式 XML Java
Spring的生命周期及Spring Bean单例和多例---超详细教学
Spring的生命周期及Spring Bean单例和多例---超详细教学
1611 0
|
XML Java 数据格式
spring之bean的生命周期以及单例多例的区别
spring之bean的生命周期以及单例多例的区别
492 0
|
Java Spring 容器
解读spring5源码中实例化单例bean的调用链
解读spring5源码中实例化单例bean的调用链