How can I inject dependencies into objects that weren’t created by a DI framework?
I am running an application on Google App Engine using Objectify, so POJOs are created by Objectify when data is fetched from the datastore. Personally i like having convenience methods to get related objects, like car.getOwner().getName() The car object is created by Objectify. The code of getOwner() owner would be something like
public Person getOwner(){
return PersonService.getById(this.ownerId);
}
I could improve it with a ServiceLocator
public Person getOwner(){
return ServiceLocator.getService(PersonService.class).getById(this.ownerId);
}
But how would I do this with DI?
I looked at Guice, but i can only think of putting the Injector in a singleton and access it from the getOwner method.
Is my thinking flawed?
If you are using Objectify4 you can subclass ObjectifyFactory and override the construct() method. This will allow you to inject your entity classes.
You can see an example here: https://github.com/stickfigure/motomapia/blob/master/java/com/motomapia/OfyFactory.java