When a spring bean is scoped as a prototype, the Spring IoC container creates new bean instance every time when a request is made for that bean. We can define the scope of a bean as prototype using scope="prototype" attribute of element or using @Scope(value = ConfigurableBeanFactory. SCOPE_PROTOTYPE) annotation.
If the scope is set to prototype, the Spring IoC container creates a new bean instance of the object every time a request for that specific bean is made. As a rule, use the prototype scope for all state-full beans and the singleton scope for stateless beans.
In Spring, scope can be defined using spring bean @Scope annotation. Let's quickly list down all six inbuilt bean scopes available to use in spring application context. These same scope apply to spring boot bean scope as well. Opposite to singleton, it produces a new instance each and every time a bean is requested.
We can define the scope of a bean as prototype using scope="prototype" attribute of <bean/> element or using @Scope(value = ConfigurableBeanFactory. SCOPE_PROTOTYPE) annotation. In this post we will learn how to create a bean, scoped as prototype, using @Scope annotation.
You can use the @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
annotation.
@Service
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class CustomerService {
// ...
}
As of the current spring version 4.3.2
, we can use @Scope("prototype") annotation.
@Scope("prototype")
@Repository
public class MovieFinderImpl implements MovieFinder {
// ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With