36

Is it possible to convert the following XML configuration to an annotation based one?

<bean id="myBean" class="my.package.MyBeanClass" scope="prototype" />

I'm using Spring 2.5.6.

3 Answers3

72

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.
DJDaveMark
  • 2,669
  • 23
  • 35
ManuPK
  • 11,623
  • 10
  • 57
  • 76
  • 9
    There's also a nice constant to use instead of the String: [`BeanDefinition.SCOPE_PROTOTYPE`](http://static.springsource.org/spring/docs/2.5.3/api/org/springframework/beans/factory/config/BeanDefinition.html#SCOPE_PROTOTYPE) –  Nov 29 '12 at 10:25
  • 6
    In the Scope annotation Javadoc, the constant recomeded is [ConfigurableBeanFactory.SCOPE_PROTOTYPE](http://docs.spring.io/spring/docs/3.2.5.RELEASE/javadoc-api/org/springframework/beans/factory/config/ConfigurableBeanFactory.html#SCOPE_PROTOTYPE) – jfcorugedo Jan 28 '14 at 17:33
  • Has BeanDefinition class removed in Spring 4 ? – Mushtaq Jameel Jun 06 '14 at 12:14
  • 1
    @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) – ameet chaubal Feb 26 '15 at 15:30
  • Or save a little typing with `@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)` – mjaggard Dec 12 '17 at 13:55
  • Is there any reasoning behind the fact that there is a `@RequestScope` annotation but no `@PrototypeScope`? – Peter Wippermann Sep 26 '18 at 10:46
7

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

@Scope("prototype")
@Repository
public class MovieFinderImpl implements MovieFinder {
    // ...
}
Omkar Puttagunta
  • 4,036
  • 3
  • 22
  • 35
0

In Spring 5, You can use as follows

@Component("myBean")

@Scope("prototype")

public class MyBeanClass{//your logics}