Spring 3.2.4升级至4.3.8后singleton="false"失效的解决方案及疑问
Great question! Since you're upgrading from Spring 3.2.4 to 4.3.8, let's break down these two points clearly for you:
1. 在Spring 4.3.8中实现singleton="false"的配置方式
The singleton="false" attribute was a legacy approach for defining non-singleton beans in older Spring versions, and it's been deprecated in favor of the more explicit scope attribute. Here's how you can replicate the same behavior in 4.3.8:
XML配置方式
Instead of setting singleton="false", directly specify the bean's scope as prototype:
<bean id="yourCustomBean" class="com.example.YourBeanClass" scope="prototype"/>
注解配置方式
If you're using annotation-driven development, use the @Scope annotation on your bean class or @Bean method:
- On the bean class:
import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; @Component @Scope("prototype") public class YourBeanClass { // Bean logic here }
- On a
@Beanmethod in a configuration class (type-safe alternative):
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.context.annotation.Scope; @Configuration public class AppConfig { @Bean @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) public YourBeanClass yourCustomBean() { return new YourBeanClass(); } }
2. singleton="false"是否等价于Prototype作用域?
Yes, they are completely equivalent.
In Spring's design, setting singleton="false" in older versions tells the container to create a new bean instance every time it's requested (whether via getBean() calls or dependency injection). This is exactly the core behavior of the prototype scope.
The switch to scope="prototype" was made to make configuration more consistent and explicit—since the scope attribute supports additional bean scopes like request, session, or application, whereas the old singleton boolean only handled the binary choice between singleton and non-singleton.
内容的提问来源于stack exchange,提问作者user3710686

