java 代码scope注解_Spring学习(15)--- 基于Java类的配置Bean 之 @Bean @Scope 注解
默認(rèn)@Bean是單例的,但可以使用@Scope注解來(lái)覆蓋此如下:
@Configuration
public class MyConfiguration {
@Bean
@Scope("prototype")
public MovieCatalog movieCatalog(){
//...
}
}
Bean的作用域包括singleton、prototype、request、session、global session
例子:
新建接口Store及實(shí)現(xiàn)類(lèi)StoreImpl
package com.scope;
public interface Store {
}
package com.scope;
public class StoreImpl implements Store {
}
java config 實(shí)現(xiàn)
package com.scope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
@Configuration
public class StoreConfig {
@Bean
@Scope("prototype")
public Store stringStore(){
return new StoreImpl();
}
}
XML配置:
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.1.xsd">
單元測(cè)試:
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());
}
}
結(jié)果:
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 hierarchy
2015-7-8 9:47:11 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [spring-beanannotation.xml]
1152423575
628012732
結(jié)果發(fā)現(xiàn),兩個(gè)對(duì)象的hashcode不一樣,說(shuō)明每次取出的都是新的對(duì)象。
總結(jié)
以上是生活随笔為你收集整理的java 代码scope注解_Spring学习(15)--- 基于Java类的配置Bean 之 @Bean @Scope 注解的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: LSB最低有效位和MSB最高有效位
- 下一篇: java表格更新javadb_Java解