JdbcTemplate.update() 中的 NullPointerException

NullPointerException in JdbcTemplate.update()

我是 spring 的新手,尝试使用 PostgeSQL spring jdbc 并在 JdbcTemplate.update() 的 DAO class 中得到 NullPointerException。内容如下:

pom.xml

<!-- Spring JDBC Support -->
     <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>4.0.2.RELEASE</version>
    </dependency>
   <!-- postgreSQL Driver -->          
    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <version>9.4-1200-jdbc41</version>
    </dependency>

servlet-context.xml

<!-- declare datasource bean -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="org.postgresql.Driver" />
    <property name="url" value="jdbc:postgresql://localhost:5432/notesHero" />
    <property name="username" value="postgres" />
    <property name="password" value="postgres" />
</bean>

DAOImpl class

  @Component
 public class AdvertiseDAOImpl implements AdvertiseDAO 
  {

private JdbcTemplate template;
@Autowired
private DataSource dataSource;

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

    /*public AdvertiseDAOImpl(DataSource dataSource) {
        template = new JdbcTemplate(dataSource);
    }*/

@Override
public void save(Advertise ad) {
    // TODO Auto-generated method stub
    String insertQry = "INSERT INTO ad_master (name, email_id) values (?,?)";
    System.out.println(ad.getName() + ad.getEmail());
    template.update(insertQry, ad.getName(), ad.getEmail());
}

@Override
public void delete(long postId) {
    // TODO Auto-generated method stub

}

@Override
public Advertise get(long postId) {
    // TODO Auto-generated method stub
    return null;
}

}

在这方面的任何帮助将不胜感激..

问题在这里:

@Autowired
private DataSource dataSource;

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

你在字段上自动装配,因此你的 setter 方法永远不会被调用,因此你的模板变量保持未初始化(或默认为空)。

所以不用自动装配字段自动装配 setter 方法。

问题可能是Spring没有调用方法

public void setDataSource(DataSource dataSource)

接线时

@Autowired
private DataSource dataSource; 

您可以在 Spring 通过将此方法添加到 class AdvertiseDAOImpl

完成数据源的自动装配后初始化 JdbcTemplate
@PostConstruct
public void initialize() {
    template = new JdbcTemplate(dataSource);
}

或者,您可以定义一个 JdbcTemplate bean,并通过将 @Autowired 注释添加到 private JdbcTemplate template; 字段来自动装配它。