2015-02-23 84 views
0

我是Spring的新手,嘗試使用PostgeSQL的spring jdbc並在JdbcTemplate.update()的DAO類中獲取NullPointerException。內容如下:JdbcTemplate.update()中的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類

@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; 
} 

} 

在這方面的任何幫助將高度讚賞..

回答

0

該問題可能是春天不會調用方法

public void setDataSource(DataSource dataSource) 

接線

@Autowired 
private DataSource dataSource; 

就可以初始化你的JdbcTemplate後春天完成加入此方法類AdvertiseDAOImpl

自動裝配的數據源時
@PostConstruct 
public void initialize() { 
    template = new JdbcTemplate(dataSource); 
} 

或者,您可以定義一個JdbcTemplate bean並通過將@Autowired註釋添加到private JdbcTemplate template;字段來使其自動裝配。

1

問題就在這裏:

@Autowired 
private DataSource dataSource; 

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

您自動裝配現場,因此您的setter方法不會被調用,因此你的模板變量仍然未初始化(或默認空值)。

所以不是自動裝配字段autowire setter方法。