I wouldn't advise you to code the class to be instantiated, along with
constructor arguments, in a property file.
I think a much better way is to:
- create a DogModule (in addition to any other, more general, Module)
that binds Animal.class to Dog or provides a Dog)
- implement some kind of discovery of Modules in the classpath (this
could possibly go also in a property file, to make it simpler), and add
each of the discovered modules.
If you want to replace the Dog with a Cat, then you would have to
replace DogModule with CatModule.
On 18-05-2011 19:13, leo wrote:
Hi. I just started to experiment with Guice and have a question. What
is the best way to do the following:
- I have an abstract class Animal
- Want to start the application with a specific implementation of the
Animal class say Dog
- I specify "animalClass = Dog" in a properties file.
- To create a Dog I need to pass many parameters, say:
dog.breed = pitbull
dog.weight = 40
...
In AnimalModule I do this:
@Provides
Animal provideDog() {
Animal dog = new Dog(
config.getString("dog.breed"),
config.getInt("dog.weight"),
...
);
return dog;
}
This works fine. I can get my dogs in some class as follows:
Injector injector = Guice.createInjector(new AnimalModule());
Animal dog = injector.getInstance(Dog.class);
My question is how can I do this without hardcoding Dog in the module.
Say tomorrow I want to create a Cat with another set of parameters. I
can see how to load components in Spring and other frameworks but I
want to keep this lightweight and I don't want to write framework code
to do this with reflection. Thoughts?
Thanks,
-leo
--
You received this message because you are subscribed to the Google Groups
"google-guice" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/google-guice?hl=en.