首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

Spring MVC 刪除功能報 500 錯誤:NullPointerException 深度排查與修復

     編輯:程式設計疑難解答

錯誤堆疊分析

java.lang.NullPointerException
    at com.pengyou.service.impl.delServiceImpl.delreg(delServiceImpl.java:23)
    ...

錯誤明確指向 delServiceImpl.java 第 23 行發生空指標異常,經分析該行為 deldao.delreg(id);,表明 deldao 依賴注入失敗,為 null。

程式碼結構審視

DAO 實作層

@Repository("deldao")
public class delDaoImpl implements IdelDao {
    @Resource
    protected SessionFactory sessionFactory;
    // ...
    @Override
    public void delreg(int id) {
        Session session = this.getSession();
        registryEntity regens = new registryEntity();
        regens.setId(id);
        session.delete(regens);
    }
}

Service 實作層 - 關鍵問題所在

@Service("delservice")
public class delServiceImpl implements IdelService {
    private IdelDao deldao;  // 缺少 @Resource 或 @Autowired 註解!
    
    @Override
    public void delreg(int id) {
        System.out.println("delServiceImpl---1------>" + id);
        deldao.delreg(id);  // 第23行:deldao 為 null
        System.out.println("delServiceImpl--------->" + id);
    }
}

Controller 層

@Controller
@RequestMapping("/del/")
public class delController extends BaseController {
    @Resource
    private IdelService idelservice;
    // ...
}

核心修復方案

在 delServiceImpl 中為 deldao 欄位加入依賴注入註解:

@Service("delservice")
public class delServiceImpl implements IdelService {
    @Resource  // 或 @Autowired
    private IdelDao deldao;  // 修復:注入 DAO 依賴
    
    @Override
    @Transactional  // 建議在方法層級加上事務註解
    public void delreg(int id) {
        System.out.println("delServiceImpl---1------>" + id);
        deldao.delreg(id);
        System.out.println("delServiceImpl--------->" + id);
    }
}

DAO 層優化建議

原始碼中 session.delete(regens) 使用新建實體刪除,雖可行但不符合 Hibernate 最佳實踐。建議改為:

@Override
public void delreg(int id) {
    Session session = this.getSession();
    registryEntity regens = (registryEntity) session.get(registryEntity.class, id);
    if (regens != null) {
        session.delete(regens);
    }
}

此寫法先載入持久化物件再刪除,可觸發攔截器、級聯刪除等機制,且能避免刪除不存在實體拋出異常。

其他潛在問題檢查清單

  • 確認 IdelDao 介面與 delDaoImpl 實作類的 bean 名稱一致(@Repository("deldao"))
  • 檢查 Spring 設定檔是否掃描 com.pengyou.dao.impl 與 com.pengyou.service.impl 套件
  • 驗證 sessionFactory bean 正確注入 DAO 層
  • 前端 JSP 刪除連結需正確傳遞 id 參數

除錯技巧總結

  1. 閱讀堆疊追蹤定位具體行號
  2. 檢查該行涉及的物件是否為 null
  3. 追溯物件初始化路徑(建構子、Setter、依賴注入)
  4. 驗證 Spring 容器掃描與註解配置
  5. 單元測試隔離驗證各層邏輯
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved