Spring组件注册注解之@Scope

目录

1. 说明

2. 注解说明

3. 注解用法

4. 组件依赖组件


1. 说明

@Scope是指定IOC组件的作用域,是单例存在的还是多例的等等,对应的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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

	<bean id="person" class="com.yibai.spring.annotation.bean.Person" scope="prototype" />

</beans>

2. 注解说明

@Scope可选值有4个

        singleton:Spring IOC容器中只会存在一个共享的bean实例,并且所有对bean的请求,只要id与该bean定义相匹配,则只会返回bean的同一实例;
        prototype:每一次请求都会产生一个新的bean实例,相当与一个new的操作,对于prototype作用域的bean,Spring不会对一个prototype的bean的整个生命周期管理,IOC将装配好的实例返回个客户端之后,该bean的操作处理都由客户端管理;
        request:在Web应用中,request表示该针对每一次HTTP请求都会产生一个新的bean,同时该bean仅在当前HTTP request内有效;
        session:在Web应用中,request表示该针对每一次HTTP请求都会产生一个新的bean,同时该bean仅在当前HTTP request内有效;

3. 注解用法

当被@Component, @Repository, @Service, @Controller或者已经声明过@Component自定义注解标记时

@Configuration
public class MainConfigForScope {

	@Bean
	@Scope(value = "prototype")
	public Address address() {
		return new Address();
	}

}

当使用@Bean标记,通过方法返回时

@Setter
@Getter
@ToString
@Component
@Scope(value = "singleton")
public class Address {
	private String country;
	private String province;
	private String detail;
}

4. 组件依赖组件

    当Person依赖Address: 
        当Address是prototype,Person是singleton时,每一次请求Address都是新组装的bean,每一次请求Person的时候,Person是单例的,自然依赖的Address也是同一个;
        当Address是singleton,Person是prototype时,Person是多例的,但是所有Person依赖的Address是同一个;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值