Spring Bean的prototype无用的解决

简介: spring 的bean默认是单例,这个用spring的人基本都知道。 如果需要多个实例,又要使用ioc怎么办呢? 当然是使用@Scope注解,指明ConfigurableBeanFactory.SCOPE_PROTOTYPE了。

spring 的bean默认是单例,这个用spring的人基本都知道。

如果需要多个实例,又要使用ioc怎么办呢?

当然是使用@Scope注解,指明ConfigurableBeanFactory.SCOPE_PROTOTYPE了。

/**
	 * Scope identifier for the standard singleton scope: "singleton".
	 * Custom scopes can be added via {@code registerScope}.
	 * @see #registerScope
	 */
	String SCOPE_SINGLETON = "singleton";

	/**
	 * Scope identifier for the standard prototype scope: "prototype".
	 * Custom scopes can be added via {@code registerScope}.
	 * @see #registerScope
	 */
	String SCOPE_PROTOTYPE = "prototype";

 

但是在使用过程中 发现这样依然是单例。

难道spring的注解不稳定还是我使用有误?

 

首先推敲一下,为什么我们获取到的实例每次都一样。

spring出问题是不太可能了,这么常见的特性那么多人都用呢。

 

如果给一个组件加上

@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)

 每次请求它的实例,spring的确会给返回一个新的。

问题是这个多例对象是被其他单例服务依赖的。

而单例服务初始化的时候,多例对象就已经被创建好了。当你去使用单例服务的时候,多例对象也不会被再次创建了。

 

那怎么解决呢?

一个首先想到的方法当然是注入多个,就是写多个@Autowired。

这样的确可以。而且如果对单例服务写多个,他们也是一样的,只有对多例的才行。

 

但是我们的服务绝大多数时候都不知道需要多少多例服务,服务是动态创建的。

所以另一种方法就是使用getBean方法:

@Autowired
private ApplicationContext applicationContext;

applicationContext.getBean()

 只要每次调用getBean就可以获得一个新服务。

 

 其实spring的@Scope注解提供了在单例服务里使用多例对象的能力,它提供了一个代理字段

/**
	 * 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;

 默认是不使用代理创建。我们只要把它改成使用代理即可:

@Component
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE, proxyMode = ScopedProxyMode.TARGET_CLASS)

 这样即使是在单例里面使用,每次获取多例对象也会拿到一个新的。

 

目录
相关文章
|
3天前
|
安全 Java Spring
Spring框架中的单例Bean是线程安全的吗?
Spring框架中的单例Bean是线程安全的吗?
10 1
|
3天前
|
XML 前端开发 Java
【JavaEE】深入了解Spring中Bean的可见范围(作用域)以及前世今生(生命周期)
【JavaEE】深入了解Spring中Bean的可见范围(作用域)以及前世今生(生命周期)
7 0
|
3天前
|
存储 缓存 Java
【JavaEE】Spring中注解的方式去获取Bean对象
【JavaEE】Spring中注解的方式去获取Bean对象
3 0
|
3天前
|
存储 Java 对象存储
【JavaEE】Spring中注解的方式去存储Bean对象
【JavaEE】Spring中注解的方式去存储Bean对象
7 0
|
3天前
|
存储 Java 对象存储
【JavaEE】DI与DL的介绍-Spring项目的创建-Bean对象的存储与获取
【JavaEE】DI与DL的介绍-Spring项目的创建-Bean对象的存储与获取
9 0
|
3天前
|
消息中间件 安全 Java
在Spring Bean中,如何通过Java配置类定义Bean?
【4月更文挑战第30天】在Spring Bean中,如何通过Java配置类定义Bean?
21 1
|
3天前
|
XML Java 数据格式
Spring Bean
【4月更文挑战第30天】Spring Bean
17 0
|
3天前
|
前端开发 Java 数据格式
【Spring系列笔记】定义Bean的方式
在Spring Boot应用程序中,定义Bean是非常常见的操作,它是构建应用程序的基础。Spring Boot提供了多种方式来定义Bean,每种方式都有其适用的场景和优势。
32 2
|
3天前
|
XML Java 数据格式
谈谈 Spring 中 Bean 的生命周期?
谈谈 Spring 中 Bean 的生命周期?
20 1
|
3天前
|
XML Java 数据格式
Spring Bean的定义(含创建Bean的三种方式)
Spring Bean的定义(含创建Bean的三种方式)