Für mein gegenwärtiges Freizeit-Projekt OpenRanked war es nötig, dass ich beim Starten der Applikation (Stand-Alone Anwendung ohne Anwendungsserver) ein Pfad zu einer .properties-Datei mit den Einstellungen des Servers übergeben konnte. Damit nun die übergebene .properties-Datei auch in der richtigen zeitlichen Reihenfolge geladen werden konnte, ist folgender Code-Schnipsel nötig:

// _xmlFiles = new String[] { "config.xml" }
// false = Context noch nicht initalisieren
ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext(
_xmlFiles, false);
// PropertyPlacer aufsetzen, so dass die Konfiguration geladen werden kann
PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer();
Resource resource  = ac.getResource("my.properties");

if (resource == null)
{
throw new InvalidParameterException(
"Could not load configuration");
}

// Location setzen
cfg.setLocation(resource);
// Dem ApplicationContext den PostProcessor anfügen
ac.getBeanFactoryPostProcessors().add(cfg);

// ApplicationContext (neu) laden
ac.refresh();

Warum ich das poste? Die Spring-Dokumentation schlägt vor, dass anstatt ac.getBeanFactoryPostProcessors() cfg.setBeanFactory(ac.getBeanFactory()) benutzt werden soll. Das funktioniert aber nicht, weil in dem Moment der ApplicationContext noch gar nicht geladen wurde und es dann zu Exceptions kommt.

I am asking you for a donation.

You liked the content or this article has helped and reduced the amount of time you have struggled with this issue? Please donate a few bucks so I can keep going with solving challenges.


0 Comments

Leave a Reply