title: Spring: Why is setter not called in spite of @Autowired annotation
body: <p>I am learning Spring. I came around using Spring with JDBC and also read about Autowiring.</p>
  
  <p>So I wrote this</p>
  
  <pre><code>public class JdbcAccess {
      @Autowired
      private DataSource dataSource;
  
      private JdbcTemplate jdbcTemplate;
  
      public void setDataSource(DataSource dataSource) {
          System.out.println("setDataSource called");
          this.dataSource = dataSource;
          this.jdbcTemplate = new JdbcTemplate(dataSource);
      }
  
      public void getCount1() {
          String sql= "SELECT COUNT(*) FROM MYTABLE";
          jdbcTemplate = new JdbcTemplate();
          jdbcTemplate.setDataSource(getDataSource());
          int count = jdbcTemplate.queryForInt(sql);      
          System.out.println("Result is = " + count);
      }
  
      public void getCount2() {
          String sql= "SELECT COUNT(*) FROM MYTABLE";
          int count = jdbcTemplate.queryForInt(sql);        // Line 66
          System.out.println("Count = " + count);
      }
  }
  </code></pre>
  
  <p>I expect below as output:</p>
  
  <pre><code>setDataSource called
  Count = 3
  </code></pre>
  
  <p>What I get:</p>
  
  <pre><code>Exception in thread "main" java.lang.NullPointerException at playwithspring.JdbcAccess.getCount2(JdbcAccess.java:66)
  </code></pre>
  
  <p>This means <code>setDataSource(..)</code>, isn't being called by Spring, but Spring framework is setting the data source correctly, because <code>getCount1()</code>, which makes a call to <code>getDataSource()</code> runs fine. So my questions are:</p>
  
  <ul>
  <li>Then <strong>how is Spring setting dataSource</strong> without calling setter ?</li>
  <li><strong>What I can do</strong> in above program <strong>to achieve</strong> desired <strong>output</strong> ?</li>
  </ul>
  
  <p><strong>Please note:</strong> I run either <code>getCount1()</code> or <code>getCount2()</code></p>