質問

This is what I have tried so far.
DaoImpl.java

@Component
public class DaoImpl {
  @Autowired
  private DataSource dataSource;
  private JdbcTemplate jdbcTemplate;

  public DataSource getDataSource() {
    return dataSource;
  }

  public void setDataSource(DataSource dataSource) {
    this.jdbcTemplate = new JdbcTemplate(dataSource);
      }

  public JdbcTemplate getJdbcTemplate() {
    return jdbcTemplate;
  }

  public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
    this.jdbcTemplate = jdbcTemplate;
  }

  public int getCircleCount() {
    String sql = "select count(*) from circle";
    return (Integer)getJdbcTemplate().queryForObject(sql, Integer.class); //throws NPE
    //return getJdbcTemplate().queryForInt(sql);
  }
}

spring.xml

<bean id="dataSource"
    class="org.apache.commons.dbcp2.BasicDataSource">
    <property name="driverClassName" value="org.apache.derby.jdbc.ClientDriver" />
    <property name="url" value="jdbc:derby://localhost:1527/db" />
    <property name="initialSize" value="2"/>
    <property name="maxTotal" value="5"/>
</bean>

But I'm getting Null Pointer Exception at return statement of getCircleCount(). I'm learning Spring JDBC. Please help.

役に立ちましたか?

解決

The problem is that the datasource gets injected directly into the field, but the setter is never called.

You need to move the @Autowired annotation from the field to the setter like so.

@Autowired
public void setDataSource(DataSource dataSource) {
    this.jdbcTemplate = new JdbcTemplate(dataSource);
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top