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

本文深入探讨Spring框架中基于Java类的配置Bean,重点介绍默认的单例作用域以及如何通过@Scope注解覆盖为原型作用域,通过实例演示了如何在Java配置类中实现不同作用域的Bean,并提供了相应的单元测试验证。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值