![](/img/trans.png)
[英]Getting nullpointerException while using the jdbcTemplate in spring
[英]NullPointerException while accessing an instance of Spring JdbcTemplate
我正在嘗試使用 Spring JDBCTemplate 類來訪問數據庫。 作為第一個教程,我使用了 xml spring 配置文件,一切都按預期工作。 現在,我正在嘗試使用@Configuration
並通過此文件中的@Bean
注釋創建DataSource
和JdbcTemplate
實例。 但是,我在int result = template.update(sql);
處得到一個 NullPointerException
我確定我犯了一個愚蠢的錯誤。 想知道它可能是什么。
代碼如下。
@Configuration
public class SpringJDBCAnnotation {
@Autowired
static JdbcTemplate template;
@Autowired
static DataSource dataSource;
@Bean
DataSource dataSource() {
DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setDriverClassName("com.mysql.jdbc.Driver");
ds.setUrl("jdbc:mysql://localhost:3306/organization");
ds.setUsername("root");
ds.setPassword("test");
return ds;
}
@Bean
JdbcTemplate template() {
JdbcTemplate template = new JdbcTemplate();
template.setDataSource(dataSource);
return template;
}
public static void main(String[] args) {
String sql = "insert into employee values(1, 'Tom', 'Cruise')";
int result = template.update(sql);
System.out.println("# of records inserted : " + result);
}
}
每當我們需要創建 bean 或自動裝配它們時,都需要獲取應用程序上下文。
由於這是基於 Java 的配置,因此檢索如下。
ApplicationContext context = new AnnotationConfigApplicationContext(SpringJDBCAnnotation.class);
並且需要像往常一樣從上下文訪問 bean。
JdbcTemplate template = context.getBean(JdbcTemplate.class);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.