Kevin
Kevin

Reputation: 6292

How to make a factory that creates singleton in Spring

I have an object that must be created using a factory method:

public class FrameFactory {
    public static Frame createFrame() throws IOException, SerializationException {
        BXMLSerializer bxmlSerializer = new BXMLSerializer();
        return (Frame)bxmlSerializer.readObject(FrameFactory.class, "/gui/MainFrame.bxml");
    }
}

The Spring call to get the mean will be something like this:

<bean id="frame" class="Frame" factory-method="createFrame"/>

However, I want this object to be singleton.

My question is that does Spring has some ready-made method to make a singleton OR I have to implement the singleton pattern myself in the FrameFactory?

Thank you very much.

Upvotes: 2

Views: 463

Answers (1)

Serge Ballesta
Serge Ballesta

Reputation: 148965

As you use a static factory method, the correct syntax is :

<bean id="frame" class="FrameFactory " factory-method="createFrame"/>

and you do not have to create a factory bean. By default, frame bean will be instanciated as a singleton bean.

Upvotes: 2

Related Questions