您的位置:首页 > 编程语言 > Java开发

Spring学习(15)--- 基于Java类的配置Bean 之 @Bean & @Scope 注解

2015-07-07 23:01 1001 查看
默认@Bean是单例的,但可以使用@Scope注解来覆盖此如下:

@Configuration
public 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;

@Configuration
public class StoreConfig {

@Bean
@Scope("prototype")
public Store stringStore(){
return new StoreImpl();
}
}


XML配置:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
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"> 
<context:component-scan base-package="com.scope">
</context:component-scan>

</beans>


单元测试:

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 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


结果发现,两个对象的hashcode不一样,说明每次取出的都是新的对象。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: