jdbcTemplate通过@Autowired自动注入时,值为null的问题

这篇博客探讨了在Spring框架中如何正确使用依赖注入。错误示例展示了直接使用`new`关键字创建对象,而正确的做法是通过ApplicationContext获取Bean,或者在测试类中使用`@RunWith`和`@ContextConfiguration`注解来加载上下文。这确保了对象的生命周期由Spring管理,符合IoC原则。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//Dao接口实现类,注入 jdbcTemplate
1. @Autowired
    private JdbcTemplate jdbcTemplate;
//错误示范,不能直接new,应该交给IOC处理
2.AccountImp accountImp =  new AccountImp();
//正确做法
 3.ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
        AccountImp accountImp = (AccountImp) applicationContext.getBean("accountImp");
或者
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring.xml"})
public class PublicTest {
           
}
public class AccountCURD extends PublicTest {

    @Autowired
    AccountImp accountImp;
}    
在抽象类中入`JdbcTemplate`时,需要意一些细节。如果您在抽象类中入`JdbcTemplate`,并且在子类中使用它,可能会出现`NullPointerException`异常。 这是因为在入`JdbcTemplate`时,Spring并不会知道应该将哪个`JdbcTemplate`入到哪个子类中。因此,您需要通过在子类中使用`@Qualifier`解来指定要入的`JdbcTemplate`。 以下是一个示例代码,展示了如何在抽象类中入`JdbcTemplate`并在子类中使用它: ```java @Component public abstract class AbstractRepository { @Autowired @Qualifier("jdbcTemplate") private JdbcTemplate jdbcTemplate; public JdbcTemplate getJdbcTemplate() { return jdbcTemplate; } } ``` 在上面的代码中,我们在抽象类`AbstractRepository`中入了`JdbcTemplate`,并在`getJdbcTemplate()`方法中返回它。请意,我们使用了`@Qualifier`解来指定要入的`JdbcTemplate`。 现在,让我们看看一个子类`UserRepository`的例子,它继承了`AbstractRepository`,并使用了`getJdbcTemplate()`方法来执行SQL查询: ```java @Repository public class UserRepository extends AbstractRepository { public List<User> findAll() { String sql = "SELECT * FROM users"; return getJdbcTemplate().query(sql, new BeanPropertyRowMapper<>(User.class)); } } ``` 在子类中,我们可以调用`getJdbcTemplate()`方法来获取父类中入的`JdbcTemplate`,并使用它来执行SQL查询。 这样,我们就可以在抽象类中入`JdbcTemplate`并在子类中使用它,同时避免了`NullPointerException`异常。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值