org.springframework.beans.factory.NoSuchBeanDefinitionException:
No matching bean of type [com.xxx.xxx.service.UserService] found for dependency
明確提示:Spring 容器中**找不到** UserService 類型的 Bean。
| 配置文件 | 掃描包路徑 | 加載的 Bean |
|---|---|---|
springmvc-servlet.xml (Web 容器) | com.xxx.xxx.controllercom.xxx.xxx.servicecom.xxx.xxx.serviceimpl | Controller、Service、ServiceImpl、DAO 全部 |
applicationContext.xml (根容器) | com.xxx.xxx.daocom.xxx.xxx.daoimplcom.xxx.xxx.servicecom.xxx.xxx.serviceimpl | DAO、Service、ServiceImpl(無 Controller) |
測試類 @ContextConfiguration | 同時加載上述兩個 XML | **理論上應全量加載**,但實際可能因加載順序/覆蓋導致 ServiceImpl 未掃描到 |
UserServiceImpl 所在包是否真在 com.xxx.xxx.serviceimpl,且類上標註 @Service("userServiceImpl")springmvc-servlet.xml 可能拿不到根容器的 Service Beanclasspath*:**/applicationContext.xml 可能匹配到多個文件,導致重複/覆蓋定義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>
@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"));
}
}
@Autowired
private ApplicationContext ctx;
@Test
public void checkBeans() {
String[] names = ctx.getBeanNamesForType(UserService.class);
System.out.println("UserService beans: " + Arrays.toString(names));
// 應輸出 [userServiceImpl] 或類似
}
UserService,實現類 @Service 標註無誤@Transactional 可自動回滾,保持數據庫乾淨@Sql 或 DbUnit 初始化測試數據,別依賴開發庫@SpringBootTest 一行搞定,無需手寫 XML「測試配置獨立於生產配置,掃描路徑顯式精確,Bean 註冊可驗證。」