title: Injecting specific objects into specific constructors with Guice
body: <p>I am constructing a variable amount of KlasseA-objects and a corresponding amount of KlasseB-objects.</p>
  
  <p>KlasseA depends on ClassZ and ClassY, KlasseB depends on ClassZ, ClassY and KlasseA. KlasseA &amp; KlasseB have to use the same instance of ClassY since it has an external connection which has to be used by both classes. BUT when I create another pair of KlasseA &amp; KlasseB objects both have to use a new instance of ClassY, since they may not use the same connection as the other 2 KlasseA &amp; KlasseB objects.</p>
  
  <p>So far I have used Guice to inject the dependencies, but since Guice would either always create a new instance of ClassY or only one instance if I make it a singleton, it doesnt really work as I intended. </p>
  
  <p>Now I am wondering whether there is a possibility to do this with Guice or if I should rather take a different approach, like</p>
  
  <pre><code>@Inject
  public KlasseA(ClassZ classZ, ClassY classY)
  {
      classZ = classZ;
      classY = classY;
  }
  
  @Inject
  public KlasseB(ClassZ classZ, KlasseA klasseA)
  {
      classZ = classZ;
      classY = klasseA.getClassY();
      klasseA = klasseA;
  }
  </code></pre>
  
  <p>This way definitely works, but it kinda feels like a small hack, so I am wondering if someone has a better solution or something inspiring.</p>