1

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.

Kevin
  • 5,972
  • 17
  • 63
  • 87
  • are you getting different object? I don't think so. Print the `hashCode` of the returned `Frame`object. – Braj Aug 02 '14 at 09:46

1 Answers1

1

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.

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
  • OP want to get `Frame` object from `BXMLSerializer` object, is it possible without using factory method? – Braj Aug 02 '14 at 09:43
  • [Be careful not to confuse the Spring singleton with the Singleton Pattern](http://stackoverflow.com/questions/2637864/singleton-design-pattern-vs-singleton-beans-in-spring-container). You can create two beans the way you are doing it (with different ids) and they will not be == – Paul Samsotha Aug 02 '14 at 11:14
  • I know it. But if a programmer creates 2 beans of same class without reason and is surprised not having a true singleton, **he** is to blame, not Spring. – Serge Ballesta Aug 02 '14 at 18:22