Reference to singleton bean in Spring

9.8k views Asked by At

I'm new to Spring and thus apologies in advance if the questions seems to be trivial.

When I declare a bean in spring it is singleton by default. When spring initializes beans from config.xml it's using default creator. If I declare my private creator and getInstance method for a class, I don't get reference to the bean created during Spring initialization - I simply create same class again and this class is referenced when getInstance() is called any time later.

My question is how can I get reference to the singleton created during initialization (to the bean defined in config.xml) from code.

4

There are 4 answers

4
bpgergo On BEST ANSWER

If your class implements the Singleton Pattern then there is no way getInstance() will return an instance other then what Spring has created.

how can I get reference to the singleton created during initialization

Basically, you should have it injected to the other class, where you will need it. And you can also refer to it by ApplicationContext.getBean(), although it is not that elegant.

0
Marko Topolnik On

If you have a factory method in your code, then make xml configuration call that factory method instead of a constructor. DO NOT call getInstance from your Java code.

<bean id="fromFactory" class="org.example.MyFactory" factory-method="getInstance" />
0
maksimov On

I think this could be relevant to your question: Why is Spring's ApplicationContext.getBean considered bad?

There's a number of ways: you can get your bean instance from ApplicationContext, you can @Autowire it, etc.

1
serg10 On

Spring will create a single instance of your class by default. It will call the class's constructor once. I think you have confused this with the

public static void getInstance() 

idiom for singletons in Java which is an attempt to enforce in your class that you can never have more than one instance.

Spring has constructed a single instance of your class and is storing it in the Spring container ready for you to use. To get a reference to the instance Spring has created, you need to retrieve it from Spring's application context.