0

I want to create single instance of Preference By Unique Name(Bean Name).

So myBeanName1 will be one instance across the spring context. And another myBeanName2 across the spring context.

Is it possible to do like that ?I am bit confused with this @Bean annotation defined at method level.

As per my understanding @Bean will always return new(prototype) instance, whenever I call it until I use this @Scope(value = ConfigurableBeanFactory.SCOPE_SINGLETON) to control creation behavior.

(I know in spring Bean is Singleton by default.)

Please clarify.

@Bean(name="myBeanName1")
@ConfigurationProperties(prefix="proect.entity1")
public Preference entityDefault() {return new Preference();}

@Bean(name="myBeanName2")
@ConfigurationProperties(prefix="proect.entity2")
public Preference entityDefault() {return new Preference();}
Viraj
  • 1,360
  • 3
  • 18
  • 38

1 Answers1

0

The @Bean annotation marks a method as a factory for creating beans. Spring beans are singleton by default and are registered with the container at startup. If you require multiple instances, you will need to explicitly configure it's scope as prototype. Prototype beans are created on demand.

Romski
  • 1,912
  • 1
  • 12
  • 27
  • Now I understand what you are saying, Irrespective of XML or annotation they are singleton by default and manually need to specify creation pattern if you want other than singleton.Thanks – Viraj Aug 18 '15 at 07:55
  • Correct they are 2 different methods for achieving the same goal. The `@Bean` annotation is analogous to the `` element in XML. – Romski Aug 18 '15 at 11:59