title: How to use autowired (@Autowired) references from main(String[] args) method?
body: <p>I am trying to use an autowired reference from main class and am facing : </p>
  
  <blockquote>
    <p>Cannot make a static reference to the non-static field
    zipCodeLookupService.</p>
  </blockquote>
  
  <p>This is obvious. But I want to know how to handle this situation. What is the correct way of autowiring when main class is involved. My code will be as below -  </p>
  
  <p><strong>Interface class</strong> </p>
  
  <pre><code>package com.example.services;
  public interface IZipCodeLookup {
      String retriveCityForZip(String zipCode);
  }
  </code></pre>
  
  <p><strong>Service Class</strong></p>
  
  <pre><code>package com.example.services;
  
  import org.springframework.stereotype.Service;
  
  @Service
  public class ZipCodeLookupService implements IZipCodeLookup {
  
      @Override
      public String retriveCityForZip(String zipCode) {
  
          //below is mock code. actual code does a db lookup using a DAO.
          if(zipCode=="94123") return "San Francisco";
          return "not found in DB";
      }
  }
  </code></pre>
  
  <p><strong>here is the main class that requires the service class</strong></p>
  
  <pre><code>package com.example.demo;
  
  import org.springframework.beans.factory.annotation.Autowired;
  import org.springframework.boot.SpringApplication;
  import org.springframework.boot.autoconfigure.SpringBootApplication;
  
  import com.example.services.IZipCodeLookup;
  
  @SpringBootApplication
  public class AutowireWithMainClassApplication {
  
      @Autowired
      IZipCodeLookup zipCodeLookupService;
  
      public static void main(String[] args) {
          SpringApplication.run(AutowireWithMainClassApplication.class, args);
          String city;
          //this will not work, compilation error
          //Cannot make a static reference to the non-static field zipCodeLookupService
          city=zipCodeLookupService.retriveCityForZip(args[0]);
  
          System.out.println("city for zipcode " + args[0] + " is " +city);       
      }
  }
  </code></pre>
  
  <p>Could someone suggest - how or what is the correct way of using autowiring when main class is involved. </p>
  
  <p>(As making the Autowired reference as static does not work anyway)<br>
  in <code>AutowireWithMainClassApplication</code> class, changing to - </p>
  
  <pre><code>@Autowired
  static IZipCodeLookup zipCodeLookupService;
  </code></pre>
  
  <p>throws</p>
  
  <blockquote>
    <p>Exception in thread "main"
    java.lang.NullPointerException</p>
  </blockquote>