title: Spring Best practice for Dependency Injection
body: <p>I have some confusion about DI in spring</p>
  
  <pre><code>public interface A{
      void methodA();
  }
  public class AImpl implements A{
      public void methodA(){
            // todo something
      }
  }
  
  public interface B{
      void methodB();
  }
  public class BImpl implements B{
       public void methodB(){
         //todo somethong
       }
  }
  </code></pre>
  
  <p>I have two interface A and B and 2 class implements it.
  So, I have 2 Class that implement interface C, it depend on Interface A and B</p>
  
  <p><strong>This is case 1:</strong></p>
  
  <pre><code>public interface C{
      void methodC();
  }
  
  public class CAutowired implements C{
      @Autowired
      private A a;
      @Autowired
      private B b;
  
      public void methodC(){
         a.methodA();
         b.methodB();
      }
  }
  </code></pre>
  
  <p><strong>File .xml config</strong></p>
  
  <pre><code>  &lt;beans&gt;
         &lt;bean id="classA" class="com.example.AImpl" /&gt;
         &lt;bean id="classB" class="com.example.BImpl" /&gt;
         &lt;bean id="classC" class="com.example.CAutowired" /&gt;
      &lt;beans&gt;
  </code></pre>
  
  <p>In this case, i have a question:
    - <strong>How to Mock A and B when i write unitTest for class CAutowired</strong></p>
  
  <p><strong>This is case 2:</strong></p>
  
  <pre><code>public class CInitInject implements C{
      private A a;
      private B b;
  
      public CInitInject(A a, B b){
         this.a = a;
         this.b = b;
      }
  
      public void methodC(){
         a.methodA();
         b.methodB();
      }
  }
  </code></pre>
  
  <p><strong>File .xml config</strong></p>
  
  <pre><code>  &lt;beans&gt;
         &lt;bean id="classA" class="com.example.AImpl" /&gt;
         &lt;bean id="classB" class="com.example.BImpl" /&gt;
         &lt;bean id="classC" class="com.example.CInitInject"&gt;
               &lt;constructor-arg ref="classA" /&gt;
               &lt;constructor-arg ref="classB" /&gt;
         &lt;/bean&gt;
      &lt;beans&gt;
  </code></pre>
  
  <p>In this case, i get DI method the same in .NET. I can Mock A and B by inject 
  into constructor. Example:</p>
  
  <pre><code>@Mock
  private A aMock;
  @Mock
  private B bMock;
  
  private C c;
  
  public void setUp(){
     c = new CInitInject(aMock, bMock);
  }
  
  @Test
  public void test(){
     // todo Test somemethod
  }
  </code></pre>
  
  <p>End of all, I have a question</p>
  
  <ol>
  <li><strong>What is best practice between case 1 and case 2?</strong></li>
  <li><strong>How to Mock it when unit test</strong> </li>
  </ol>