为了账号安全,请及时绑定邮箱和手机立即绑定

访问 Spring JdbcTemplate 实例时出现 NullPointerException

访问 Spring JdbcTemplate 实例时出现 NullPointerException

慕姐8265434 2021-08-25 10:00:33
我正在尝试使用 Spring JDBCTemplate 类来访问数据库。作为第一个教程,我使用了 xml spring 配置文件,一切都按预期工作。现在,我尝试使用@Configuration,创造DataSource并JdbcTemplate通过实例@Bean在此文件中的注释。但是,我在int result = template.update(sql);我确定我犯了一个愚蠢的错误。想知道它可能是什么。代码如下。@Configurationpublic class SpringJDBCAnnotation {@Autowiredstatic JdbcTemplate template;@Autowiredstatic DataSource dataSource;@BeanDataSource 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;}@BeanJdbcTemplate 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);}}
查看完整描述

1 回答

?
不负相思意

TA贡献1777条经验 获得超10个赞

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

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

ApplicationContext context = new AnnotationConfigApplicationContext(SpringJDBCAnnotation.class);

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

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


查看完整回答
反对 回复 2021-08-25
  • 1 回答
  • 0 关注
  • 308 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信