Frühjahr Injektion eine statische (Globale) singleton

Habe ich eine Klasse, die sieht so aus:

public class Configurator {
    private static Configurator INSTANCE = null;

    private int maxRange = 1;

    //many other properties; each property has a default value

    private static synchronized Configurator getInstance() {
        if(INSTANCE == null)
            return new Configurator();

        return INSTANCE;
    }

    public static int getMaxRange() {
        getInstance().maxRange;
    }

    public static void setMaxRange(int range) {
        getInstance().maxRange = range;
    }

    //Getters and setters for all properties follow this pattern
}

Es dient als eine Globale configuration-Objekt, das gesetzt werden kann auf app startup, und dann wird von Dutzenden von Klassen während des gesamten Projekts:

//Called at app startup to configure everything
public class AppRunner {
    Configurator.setMaxRange(30);
}

//Example of Configurator being used by another class
public class WidgetFactory {
    public void doSomething() {
        if(Configurator.getMaxRange() < 50)
            //do A
        else
            //do B
    }
}

Ich bin jetzt importieren Sie diesen code in einem Spring-Projekt, und bin gerade bei der Konfiguration meines Sprinig XML (Bohnen). Meine Vermutung ist, dass ich definieren könnte, ein einsamer Configurator bean wie so (oder so ähnlich):

<bean id="configurator" class="com.me.myapp.Configurator" scope="singleton">
    <property name="maxRange" value="30"/>
    <!-- etc., for all properties -->
</bean>

So, wenn WidgetFactory#doSomething führt, wird der Frühling bereits geladen haben die Configurator Klasse und konfiguriert es vor der Zeit.

Ist es für mich richtig ist, um die scope="singleton", oder ist das egal? Bin ich mit der Einstellung der statischen Eigenschaften richtig? Gibt es etwas, was ich tun müssen, oder betrachten Sie hier? Vielen Dank im Voraus.

InformationsquelleAutor | 2013-02-01

Schreibe einen Kommentar