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

Spring MVC JUnit 測試 @Autowired 注入失敗:Service 掃描路徑配置缺失

     編輯:程式設計綜合問答

錯誤堆疊核心信息

org.springframework.beans.factory.NoSuchBeanDefinitionException: 
No matching bean of type [com.xxx.xxx.service.UserService] found for dependency

明確提示:Spring 容器中**找不到** UserService 類型的 Bean。

配置對比:為什麼 Controller 能注入而測試類不能?

配置文件掃描包路徑加載的 Bean
springmvc-servlet.xml (Web 容器)com.xxx.xxx.controller
com.xxx.xxx.service
com.xxx.xxx.serviceimpl
Controller、Service、ServiceImpl、DAO 全部
applicationContext.xml (根容器)com.xxx.xxx.dao
com.xxx.xxx.daoimpl
com.xxx.xxx.service
com.xxx.xxx.serviceimpl
DAO、Service、ServiceImpl(無 Controller)
測試類 @ContextConfiguration同時加載上述兩個 XML**理論上應全量加載**,但實際可能因加載順序/覆蓋導致 ServiceImpl 未掃描到

根因定位

  1. 掃描路徑寫錯或漏寫:檢查 UserServiceImpl 所在包是否真在 com.xxx.xxx.serviceimpl,且類上標註 @Service("userServiceImpl")
  2. 父子容器隔離:Spring MVC 會創建父子容器,測試類若只加載 springmvc-servlet.xml 可能拿不到根容器的 Service Bean
  3. 配置文件通配符匹配失效:classpath*:**/applicationContext.xml 可能匹配到多個文件,導致重複/覆蓋定義

修正方案:統一測試專用配置

1. 創建 test-applicationContext.xml(推薦)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="https://www.springframework.org/schema/beans"
       xmlns:context="https://www.springframework.org/schema/context"
       xsi:schemaLocation="https://www.springframework.org/schema/beans
           https://www.springframework.org/schema/beans/spring-beans.xsd
           https://www.springframework.org/schema/context
           https://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 掃描所有業務層,排除 Controller -->
    <context:component-scan base-package="com.xxx.xxx">
        <context:exclude-filter type="annotation" 
            expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!-- 測試專用數據源、事務管理器等 -->
    <import resource="classpath:db-test.xml"/>
</beans>

2. 測試類精簡配置


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:test-applicationContext.xml")
public class UserTest {
    @Autowired
    private UserService service;  // 接口類型注入

    @Test
    public void userHPTest() {
        System.out.println(service.get("889e4d63ff024b29a173ab52ce174cc9"));
    }
}

3. 驗證 Bean 是否真正註冊


@Autowired
private ApplicationContext ctx;

@Test
public void checkBeans() {
    String[] names = ctx.getBeanNamesForType(UserService.class);
    System.out.println("UserService beans: " + Arrays.toString(names));
    // 應輸出 [userServiceImpl] 或類似
}

常見避坑清單

  1. 接口 vs 實現類:注入點聲明為接口 UserService,實現類 @Service 標註無誤
  2. 事務管理:測試類加 @Transactional 可自動回滾,保持數據庫乾淨
  3. 測試數據準備:用 @Sql 或 DbUnit 初始化測試數據,別依賴開發庫
  4. Spring Boot 專用:若是 Boot 項目,直接 @SpringBootTest 一行搞定,無需手寫 XML

核心原則

「測試配置獨立於生產配置,掃描路徑顯式精確,Bean 註冊可驗證。」

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved