Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to @Inject into existing object hierarchy using Guice?
    primarykey
    data
    text
    <p>I have an existing object hierarchy where some objects have fields that need to be injected. Also there are some other objects that are constructed using <a href="http://code.google.com/p/google-guice/" rel="noreferrer">Google Guice</a> and need to be injected with references to some objects from previously described object hierarchy. How do I do such kind of injection with Guice?</p> <p>The problem is that objects from existing hierarchy were not constructed using Guice, and therefore are not subject to inject process by default. There is, of course <code>injector.injectMembers()</code> method that is able to inject into existing object instance, but it does not work on object hierarchies.</p> <p>For those wondering why I can't build mentioned object hierarchy using Guice. This hierarchy represents GUI objects and is built by a GUI framework (<a href="http://pivot.apache.org/" rel="noreferrer">Apache Pivot</a>) from a declarative GUI description (in fact this process can be described as object deserialization). That way interface construction is rather simple, and I only want to inject certain service references into interface objects and vice versa (for callbacks).</p> <p>Approach I am currently about to take is described below. </p> <p>For injecting into preexisting object hierarchy just let all objects that are interested in injection implement certain interface, like:</p> <pre><code>public interface Injectable { void injectAll(Injector injector); } </code></pre> <p>Those objects would then implement this interface like so:</p> <pre><code>public void injectAll(Injector injector) { injector.injectMembers(this); for (Injectable child : children) child.injectAll(injector); } </code></pre> <p>Then I'd just call <code>mainWindow.injectAll(injector)</code> for root object in hierarchy and all objects of interest are injected.</p> <p>Not very nice solution, but gets the work done on one side. On the other side, I need to inject objects from this hierarchy. I guess it can be done via implementing custom provider for such objects.</p> <p>Is there a better solution to my problem? Maybe there is also something wrong with my approach?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload