弹簧 Bean作用域示例
这是教程系列的16个部分中的8个
教程内容:初学者春季教程
- 弹簧框架
- 春季面试题
- 春天的依赖注入(IOC)
- 基于Spring XML的配置示例
- 基于Spring 爪哇 的配置
- 在春季通过setter方法进行依赖注入
- 在春天通过构造函数进行依赖注入
- 弹簧 Bean作用域示例
- 在春季初始化集合
- 春季自动接线
- 春天的传承
- 弹簧 ApplicationContext
- 春季生命周期回调
- 春季的BeanPostProcessors
- 弹簧 中基于注释的配置
- 春季AOP 教程
在Spring中,bean范围用于确定应从Spring容器返回给调用者的bean实例类型。
春季支持5种类型的bean范围
- 单身人士 –在每个Spring IoC容器中将单个bean定义的作用域限定为单个对象实例。
- 原型 –每次请求时返回一个新的bean实例
- 请求 –每个HTTP请求返回一个bean实例。
- 会议 –每个HTTP会话返回一个bean实例。
- globalSession –每个全局HTTP会话返回一个bean实例。
在很多情况下,春天’s core 范围 s i.e.singleton and 原型 are used.By default 范围 of 豆子 is 单身人士 .
Here we will see 单身人士 and 原型 范围 s in more details.
单例豆范围
例:
有关在Eclipse IDE中配置spring的信息,请参阅 你好世界的例子
1.Country.java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
包 组织 . Arpit . 爪哇 postsforlearning; 上市 类 国家 { 串 国家的名字 ; 上市 串 getCountryName() { 返回 国家的名字 ; } 上市 虚空 setCountryName( 串 国家的名字 ) { 这个 . 国家的名字 = 国家的名字 ; } } |
2.ApplicationContext.xml
1 2 3 4 5 6 7 8 9 |
<? XML文件 版 ="1.0" 编码方式 = “ UTF-8” ?> < 豆子 XML文件 ns ="http://www.springframework.org/schema/beans" XML文件 ns : si ="http://www.w3.org/2001/XMLSchema-instance" XML文件 ns : 哎呀 ="http://www.springframework.org/schema/aop" si :schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> < 豆 ID = “国家” 类 =“ 组织 .arpit.javapostsforlearning.Country”> </ 豆 > </ 豆子 > |
3.ScopesInSpringMain.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
包 组织 . Arpit . 爪哇 postsforlearning; 进口 组织 .弹簧框架.语境.ApplicationContext; 进口 组织 .弹簧框架.语境. 支持 .ClassPathXmlApplicationContext; 上市 类 ScopesInSpringMain{ 上市 静态的 虚空 主要 ( 串 [] args ) { ApplicationContext appContext = 新 ClassPathXmlApplicationContext(“ ApplicationContext.xml”); 国家 countryObj1 = ( 国家 ) appContext . getBean ( “国家” ); countryObj1 .setCountryName( “印度” ); 系统 . 出 . 打印 (“国家的名字:”+ countryObj1 .getCountryName()); //第二次调用getBean 国家 countryObj2 = ( 国家 ) appContext . getBean ( “国家” ); 系统 . 出 . 打印 (“国家的名字:”+ countryObj2 .getCountryName()); } } |
4.运行
1 2 3 4 |
国家 名称 : 印度 国家 名称 : 印度 |
当我们第一次调用getBean并检索国家对象并将countryName设置为“india”当第二次调用getBean方法时,它什么也没做,只是返回了与countryName相同的对象“india”.
原型bean范围
ApplicationContext.xml:
1 2 3 4 5 6 7 8 9 10 |
<? XML文件 版 ="1.0" 编码方式 = “ UTF-8” ?> < 豆子 XML文件 ns ="http://www.springframework.org/schema/beans" XML文件 ns : si ="http://www.w3.org/2001/XMLSchema-instance" XML文件 ns : 哎呀 ="http://www.springframework.org/schema/aop" si :schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> < 豆 ID = “国家” 类 =“ 组织 .arpit.javapostsforlearning.Country” 范围 ="原型"> </ 豆 > </ 豆子 > |
再次运行:
当您在应用程序上运行时,将得到以下输出。
1 2 3 4 |
国家 名称 : 印度 国家 名称 :空值 |
当我们第一次调用getBean并检索国家对象并将countryName设置为“india”当第二次我们调用getBean方法时,它返回了具有countryName作为的新对象“null”.
那’关于Spring 豆 作用域的全部内容。
在下一篇文章中,我们将看到 在春季初始化集合.