访问Spring JdbcTemplate的实例时出现NullPointerException

问题描述 投票:-3回答:1

我正在尝试使用Spring JDBCTemplate类来访问数据库。作为第一个教程,我使用了xml spring配置文件,一切都按预期工作。现在,我正在尝试使用@Configuration并通过此文件中的DataSource注释创建JdbcTemplate@Bean实例。但是,我在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);


}

}
java spring jdbctemplate spring-config
1个回答
0
投票

每当我们需要创建bean或自动装配bean时,都需要获取应用程序上下文。

由于这是基于Java的配置,因此检索如下。

ApplicationContext context = new AnnotationConfigApplicationContext(SpringJDBCAnnotation.class);

并且需要像往常一样从上下文中访问bean。

JdbcTemplate template = context.getBean(JdbcTemplate.class);
© www.soinside.com 2019 - 2024. All rights reserved.