I am a beginner with Guice, I am not sure how I should configure my services. Unfortunately, most examples found on the net are trivial and solved with a few @Named properties without any kind of validation other than Null and type-safety.
I would need to initialize a service class that requires some non-trivial configuration. During initialization, it needs to scan a given directory on disk for config files, read these files, validate their content and only then it can build and return a working service object.
So basically, creating the service requires some disk IO, configuration validation and has possible side effects (=> throws exception) that should be handled and properly reported. In a non guice app I would typically do such work on application loading and terminate the process in case of problem.
I thought I could do the big initialization job in my module, create the service instance and bind it to some interface so I could inject a ready to use object later during the app lifecycle. However I have learnt in the documentation that this approach is discouraged :
So according to the example in the above doc, a possible way would be to configure the module, gets an instance from the injector and call some init() method on it. Ok it lets me call my init method manually, let me handle exceptions, but... It doesn't seem very natural to me because :
1) The service is constructed and left in a non-usable state until some method is called on it, I can live with that but only if I really have too.
2) I don't think a service should know how to extract its own configuration from disk. I would rather create an another class that builds it and returns an instance.
My other idea would be to use a (Throwing?)Provider that can create my service instance. But even so it seems doubtful because
1) The provider will create the service once when get() is called, and I guess I will have to cache it somewhere since it's a relatively heavy task. My provider then looks like a lazy singleton.
2) I am not sure how I can control where the first call to get() will occur, so I don't have a clear place to catch initialization errors
Another way I can think of would be to inject a service provider rather than bind the service class to the provider in the module, manually retrieve the Provider instance from the injector right after its creation and call the first get() myself, surrounding everything with a try-catch but it seems a bit hacky and forces me to inject a provider rather than a service just because I need to check that everything is OK once, at creation time.
I would like to know how other people are handling this problem. Any advice? Are there other solutions?