博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Spring学习(15)--- 基于Java类的配置Bean 之 @Bean & @Scope 注解
阅读量:7073 次
发布时间:2019-06-28

本文共 1810 字,大约阅读时间需要 6 分钟。

默认@Bean是单例的,但可以使用@Scope注解来覆盖此如下:

@Configurationpublic class MyConfiguration {	@Bean	@Scope("prototype")	public MovieCatalog movieCatalog(){		//...	}}

 Bean的作用域包括singleton、prototype、request、session、global session

例子:

 新建接口Store及实现类StoreImpl

package com.scope;public interface Store {}

 

package com.scope;public class StoreImpl implements Store {	}

 java config 实现

package com.scope;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.Scope;@Configurationpublic class StoreConfig {	@Bean	@Scope("prototype")	public Store stringStore(){		return new StoreImpl();	}}

 XML配置:

 单元测试:

package com.scope;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class UnitTest {		@Test	public void test(){		ApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring-beanannotation.xml");  		Store store=(Store)context.getBean("stringStore");		System.out.println(store.hashCode());				Store store2=(Store)context.getBean("stringStore");		System.out.println(store2.hashCode());			}}

 结果:

2015-7-8 9:47:11 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@36b8bef7: startup date [Wed Jul 08 09:47:11 CST 2015]; root of context hierarchy2015-7-8 9:47:11 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions信息: Loading XML bean definitions from class path resource [spring-beanannotation.xml]1152423575628012732

结果发现,两个对象的hashcode不一样,说明每次取出的都是新的对象。

 

转载于:https://www.cnblogs.com/JsonShare/p/4628801.html

你可能感兴趣的文章
Delphi 中Format的字符串格式化使用说明(转)
查看>>
Drag & drop a button widget
查看>>
【转】 java中HashMap详解
查看>>
ODAC(V9.5.15) 学习笔记(一)总论
查看>>
Linux动态库搜索路径的技巧
查看>>
关于开源的RTP——jrtplib的使用
查看>>
非常特别的一个动态规划新手教程
查看>>
android FragmentPagerAdapter的“标准”配置
查看>>
OAF 中对文字实现html效果及对超级长文本实现默认换行,messageTextInput只读后内容自动换行,...
查看>>
sql行列转换
查看>>
Myeclipse 的hadoop环境搭建
查看>>
重置mysql的root用户密码
查看>>
Why are Eight Bits Enough for Deep Neural Networks?
查看>>
带删除小图标的EditText
查看>>
loadrunner关联及web_reg_save_param方法浅析
查看>>
Jquery Mobile 百度地图 Demo
查看>>
cocos2d-x3.0 经常使用绘图方法
查看>>
shell 中 2>&1 的使用
查看>>
Oracle的rownum原理和使用(整理几个达人的帖子)
查看>>
json_encode详解,转义
查看>>