访问 Spring JdbcTemplate 实例时出现 NullPointerException

我正在尝试使用 Spring JDBCTemplate 类来访问数据库。作为第一个教程,我使用了 xml spring 配置文件,一切都按预期工作。现在,我尝试使用@Configuration,创造DataSource并JdbcTemplate通过实例@Bean在此文件中的注释。但是,我在int result = template.update(sql);


我确定我犯了一个愚蠢的错误。想知道它可能是什么。


代码如下。


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



}


}


慕姐8265434
浏览 309回答 1
1回答

不负相思意

每当我们需要创建 bean 或自动装配它们时,都需要获取应用程序上下文。由于这是基于 Java 的配置,因此检索如下。ApplicationContext context = new AnnotationConfigApplicationContext(SpringJDBCAnnotation.class);并且需要像往常一样从上下文访问 bean。JdbcTemplate template = context.getBean(JdbcTemplate.class);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java