简体   繁体   English

访问 Spring JdbcTemplate 实例时出现 NullPointerException

[英]NullPointerException while accessing an instance of Spring JdbcTemplate

I am trying to use Spring JDBCTemplate class to access database.我正在尝试使用 Spring JDBCTemplate 类来访问数据库。 As a first tutorial, I have used xml spring configuration file and everything works as expected.作为第一个教程,我使用了 xml spring 配置文件,一切都按预期工作。 Now, I am trying to use @Configuration and created DataSource and JdbcTemplate instances through @Bean annotation within this file.现在,我正在尝试使用@Configuration并通过此文件中的@Bean注释创建DataSourceJdbcTemplate实例。 But, I get a NullPointerException at int result = template.update(sql);但是,我在int result = template.update(sql);处得到一个 NullPointerException

I am sure I have done a silly mistake.我确定我犯了一个愚蠢的错误。 Was wondering what it could be.想知道它可能是什么。

The code is as follows.代码如下。

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


}

}

Application Context needs to be obtained whenever we need to create beans or autowire them.每当我们需要创建 bean 或自动装配它们时,都需要获取应用程序上下文。

Since this is Java based configuration, it is retrieved as follows.由于这是基于 Java 的配置,因此检索如下。

ApplicationContext context = new AnnotationConfigApplicationContext(SpringJDBCAnnotation.class);

and the beans needs to be accessed from the context as usual.并且需要像往常一样从上下文访问 bean。

JdbcTemplate template = context.getBean(JdbcTemplate.class);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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