Issue
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();}
Solution
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.
Answered By - Romski
Answer Checked By - Robin (JavaFixing Admin)