成员变量在定义的时候不能用自动装配的成员的方法赋值,否则会报空指针,因为这时候自动装配的对象还没有生成实例
代码如下
错误代码:
@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {
@Autowired
private QueryRunner runner;
@Autowired
ConnectionUtil connectionUtil;
// 这一行会报空指针,因为这时候connectionUtil为null
Connection conn = connectionUtil.getConnection();
@Override
public List<Account> findAllAccount() {
try{
return runner.query(conn,"select * from account",new BeanListHandler<Account>(Account.class));
}catch (Exception e) {
throw new RuntimeException(e);
}
}
正确代码
@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {
@Autowired
private QueryRunner runner;
@Autowired
ConnectionUtil connectionUtil;
//Connection conn = connectionUtil.getConnection(); // 这一行会报空指针,因为这时候connectionUtil为null
@Override
public List<Account> findAllAccount() {
try{
// 在这里直接用connectionUtil.getConnection()传入
return runner.query(connectionUtil.getConnection(),"select * from account",new BeanListHandler<Account>(Account.class));
}catch (Exception e) {
throw new RuntimeException(e);
}
}