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

相关文章
|
4月前
|
缓存 算法 安全
Spring 为啥默认把bean设计成单例的?这篇讲的明明白白的
Spring 为啥默认把bean设计成单例的?这篇讲的明明白白的
73 0
|
10月前
|
XML Java 数据格式
Spring之bean单例与多例
Spring之bean单例与多例
127 0
|
11月前
|
XML Java 数据格式
Spring系列(三)之Bean的生命周期以及Bean的单例与多例模式
Spring系列(三)之Bean的生命周期以及Bean的单例与多例模式
|
XML Java 数据格式
【Spring】Bean的生命周期与单例实现(二)
【Spring】Bean的生命周期与单例实现(二)
82 1
|
XML Java 数据格式
【Spring】Bean的生命周期与单例实现(一)
【Spring】Bean的生命周期与单例实现
75 1
|
11月前
|
XML 安全 Java
Spring框架中的单例bean是线程安全的吗?阿里一面
在 Spring 框架中,Bean 是指由 Spring IoC(Inversion of Control)容器管理的组件或对象。Bean 是 Spring 中最基本的构建块,它们由 Spring 容器实例化、组装和管理。
92 0
|
4月前
|
安全 Java Spring
Spring框架中的单例Bean是线程安全的吗?
Spring框架中的单例Bean是线程安全的吗?
63 1
|
30天前
|
安全 Java C#
Spring创建的单例对象,存在线程安全问题吗?
Spring框架提供了多种Bean作用域,包括单例(Singleton)、原型(Prototype)、请求(Request)、会话(Session)、全局会话(GlobalSession)等。单例是默认作用域,保证每个Spring容器中只有一个Bean实例;原型作用域则每次请求都会创建一个新的Bean实例;请求和会话作用域分别与HTTP请求和会话绑定,在Web应用中有效。 单例Bean在多线程环境中可能面临线程安全问题,Spring容器虽然确保Bean的创建过程是线程安全的,但Bean的使用安全性需开发者自行保证。保持Bean无状态是最简单的线程安全策略;
|
3月前
|
Java Spring 容器
解读spring5源码中实例化单例bean的调用链
解读spring5源码中实例化单例bean的调用链
|
3月前
|
安全 Java Spring
spring的controller是单例还是多例,怎么保证并发的安全
spring的controller是单例还是多例,怎么保证并发的安全
36 0