Since the bean ‘customerService’ is in singleton scope, the second retrieval by ‘custB’ will display the message set by ‘custA’ also, even it’s retrieve by a new getBean() method. In singleton, only a single instance per Spring IoC container, no matter how many time you retrieve it with getBean(), it will always return the same instance.

2. Prototype example

If you want a new ‘customerService’ bean instance, every time you call it, use prototype instead.

Popular Posts

Good tutorials! valuable links too I see in comments. Thank you folks. but where are we setting message property values in code eg singleton case? :)

Ivan

Gracias mkyong, excelentes informacion

http://www.defrog.it Luca

You saved my life man!!! :)

Jack

How do you access the annotation defined bean?

I followed the above steps to make the CustomerService class @Service and @Scope(“prototype”). However, in the App.java’s main method I use the same CustomerService custA = (CustomerService)context.getBean(“customerService”); custA.setMessage(“Message by custA”); System.out.println(“Message : ” + custA.getMessage());

It gives me the runtime exception : org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named ‘CustomerServiceAnnotation’ is defined

Jack

After second thought, looks like ClassPathXmlApplicationContext is not appropriate to be context for annotation bean. Hence context.getBean(“customerService”); does not make any sense. So which context class should I use in this case?

Many thanks

Sagar Dahagamwar

You have to use : AnnotationConfigApplicationContext instead of ClassPathXmlApplicationContext. This will solve your problem

Hi, What if I want to dispose a singleton scope bean. is that possible? thanks.

Narayan

I facing some design challenge :-

I have to instantiate a scoped bean after server start-up. It being a scoped bean doesn’t come up automatically. It is subscriber class and needs to be instantiated as soon as the server starts and it has to be scoped for the processing further.