Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create prototype scoped Spring bean with annotations?

People also ask

How do you give a prototype scope in Spring with annotation?

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.

How do you set a bean scope as a prototype?

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.

How do you set an annotation scope in Spring?

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.

Which annotation is used to define prototype bean along with the @bean annotation?

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 {
    // ...
}
  1. Spring API Docs.
  2. Example of the mapping.
  3. Scope annotation reference.

As of the current spring version 4.3.2, we can use @Scope("prototype") annotation.

@Scope("prototype")
@Repository
public class MovieFinderImpl implements MovieFinder {
    // ...
}