繁体   English   中英

访问 Spring JdbcTemplate 实例时出现 NullPointerException

[英]NullPointerException while accessing an instance of Spring JdbcTemplate

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM