I guess my post read "a little edgy": sorry about that.
They're creating the static instances it sounds like. So you have can
acquire one via some static factory method: TheirClass.getInstance(), or
some such? You want to be able to make that instance available to your
classes via @Inject, so that your classes use their static instance, right?
Assuming that's the case, I would think your binding should be as simple as
"bind(TheirClass.class).toInstance(TheirClass.getInstance());". Then use
the
@Inject TheirClass myInstanceOfTheirClass;
If the acquisition of the static instance is more complicated than
"getInstance()", create a Provider<TheirClass> or @Provides method and do
what you need to do in the overridden "get()" method.
The older apps I work are structured like:
MyServlet extends HttpServlet {..}
MyServlet#init() { MyModel.getInstance(applicationProperties, dbfactory,
logger); }
One of the modules I have installed into the injector via the
ServletListener has the @Provides method:
@Provides
MyModel createMyModel(Properties applicationProperites, DatabaseFactory
dbFactory, @Named("MyModel") Logger logger) {
return MyModel.getInstance(applicationProperties, dbfactory, logger);
}
MyGuiceServlet has an @Inject MyModel myModel in it.
The "trick" I was trying to express was that you can @Inject any instance
you have access to via Guice, but you have to figure our how to bind/provide
for each of those instances via configuring Guice to do so: via a "bind",
@Provides, Provider<T>, etc..
Since the Web app context can throw various wrenches into things, I find it
easier to deal with my problem children at the Unit test level. Create a
module with the bindings/providers that are being troublesome, then create
the unit test to beat up on them:
@Inject TheirClass theirClass;
@BeforeClass
public void setUp() throws Exception {
Injector injector = Guice.createInjector(new
MyWonkyStaticSingletonModule());
injector.injectMembers(this);
assertNotNull(theirClass);
// or
TheirClass theirClass =
injector.getInstance(TheirClass.class);
assertNotNull(theirClass);
}
Hope this helps. Again: my bad if my post came across snarky. Wasn't my
intent: just lack of do diligence on my part. Cheers!
--
You received this message because you are subscribed to the Google Groups
"google-guice" group.
To view this discussion on the web visit
https://groups.google.com/d/msg/google-guice/-/wXql9Gu8qdAJ.
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.