默认@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不一样,说明每次取出的都是新的对象。