Spring 学习三 Bean 的作用域(@Scope)

  • @Scope 源码

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Scope {

	/**
	 * Alias for {@link #scopeName}.
	 * @see #scopeName
	 */
	@AliasFor("scopeName")
	String value() default "";

	/**
	 * Specifies the name of the scope to use for the annotated component/bean.
	 * <p>Defaults to an empty string ({@code ""}) which implies
	 * {@link ConfigurableBeanFactory#SCOPE_SINGLETON SCOPE_SINGLETON}.
	 * @since 4.2
	 * @see ConfigurableBeanFactory#SCOPE_PROTOTYPE
	 * @see ConfigurableBeanFactory#SCOPE_SINGLETON
	 * @see org.springframework.web.context.WebApplicationContext#SCOPE_REQUEST
	 * @see org.springframework.web.context.WebApplicationContext#SCOPE_SESSION
	 * @see #value
	 */
	@AliasFor("value")
	String scopeName() default "";

	/**
	 * Specifies whether a component should be configured as a scoped proxy
	 * and if so, whether the proxy should be interface-based or subclass-based.
	 * <p>Defaults to {@link ScopedProxyMode#DEFAULT}, which typically indicates
	 * that no scoped proxy should be created unless a different default
	 * has been configured at the component-scan instruction level.
	 * <p>Analogous to {@code <aop:scoped-proxy/>} support in Spring XML.
	 * @see ScopedProxyMode
	 */
	ScopedProxyMode proxyMode() default ScopedProxyMode.DEFAULT;
}
  • Bean 的作用域有四个:

singleton:单实例,每次都获取同一个实例,实例的是 IOC 初始化后创建,IOC 容器负责销毁,
prototype:多实例,每次获取不同的实例,实例是在调用的创建,IOC 容器只负责创建,不负责销毁,
request:同一次请求域中有效,在 web 环境有效,
session:同一次session中有效,在 web 环境有效,

  • @Lazy 懒加载

针对的是单实例,IOC 容器初始化完成后不加载实例,在第一次获取实例时加载,以后获取都是同一个实例

猜你喜欢

转载自blog.csdn.net/qq_22925909/article/details/84932299