Google Guice: Singleton with xml deserialization support?
in my project I need a class which contains the project configuration. The configuration must be loaded from a XML file and must be a singleton.
In Guice there is a singleton scope. Now I have to "overwrite" the singleton with th开发者_运维百科e deserialized configuration.
Is this somehow possible?
Important: pelase do note that Guice was originally created to get rid of all these huge and ugly XML files used by another DI library for managing dependencies. In general, when using Guice, you should be able to -almost- completely remove any XML from your project.
But if you must, perhaps because the XML file is generated by something outside your control then consider these:
Keep your whole configuration object and create a Provider
for it, and bind it in Singleton scope. But you'll have to perform deserialization by yourself.
Or if your configuration is simply made of (name, value) pairs, then you can use java.util.Properties
whcih can be loaded from an XML file, then use Guice Names.bindProperties()
API in one of your Module
s.
Then you can directly inject each single property by using @Inject @Named
.
精彩评论