Java 访问Spring JdbcTemplate实例时发生NullPointerException

Java 访问Spring JdbcTemplate实例时发生NullPointerException,java,spring,jdbctemplate,spring-config,Java,Spring,Jdbctemplate,Spring Config,我正在尝试使用SpringJDBCTemplate类访问数据库。 作为第一个教程,我使用了XMLSpring配置文件,一切都按预期进行。 现在,我尝试使用@Configuration,并通过该文件中的@Bean注释创建DataSource和JdbcTemplate实例。但是,我在int result=template.updatesql处得到一个NullPointerException; 我肯定我犯了一个愚蠢的错误。我想知道会是什么 代码如下 @Configuration public cla

我正在尝试使用SpringJDBCTemplate类访问数据库。 作为第一个教程,我使用了XMLSpring配置文件,一切都按预期进行。 现在,我尝试使用@Configuration,并通过该文件中的@Bean注释创建DataSource和JdbcTemplate实例。但是,我在int result=template.updatesql处得到一个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);

因为你没有开始春天。不要将这些成员字段设置为静态。顺便说一句,请查看spring.io博客上的spring引导教程。@Sara好吧,这是一个很好的关于如何不使用spring的练习,它展示了除非先初始化spring,否则spring无法做任何事情。您需要让Spring创建需要自动连接的对象,这意味着Spring无法自动连接静态字段。摆脱静态变量的邪恶是创建Spring的一个重要原因。您需要像每个人告诉您的那样实例化applicationcontext,然后从中检索bean。@Nathanhughs不检索bean,而是注入它们。