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

SSH 整合報錯 No bean named 'TestService':缺少 Bean 定義或測試啟動方式錯誤

     編輯:程式設計綜合問答

錯誤訊息

org.springframework.beans.factory.NoSuchBeanDefinitionException: 
No bean named 'TestService' is defined

原因分析

單元測試使用 ClassPathXmlApplicationContext 載入 applicationContext.xml,但該配置檔:

  1. 未掃描 com.zyf.test 包 (context:component-scan 缺失或路徑錯誤)。
  2. 未手動定義 <bean id="TestService" class="com.zyf.test.TestService"/>。
  3. @Service 註解生效需 <context:annotation-config/> + 掃描。

方案一:補全 XML Bean 定義 (傳統方式)

<bean id="testService" class="com.zyf.test.TestService">
    <property name="sessionFactory" ref="sessionFactory"/>
</bean>

注意:id 建議小駝峰 testService,Java 碼中 ac.getBean("testService")。

方案二:啟用註解掃描 (推薦)

<context:component-scan base-package="com.zyf"/>
<context:annotation-config/>

確保 TestService 類上有 @Service 或 @Component。

方案三:使用 Spring TestContext 框架 (最佳實踐)

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class TestSpring {
    @Autowired
    private TestService testService; // 自動注入,無需 getBean

    @Test
    public void testSaveUsers() {
        testService.saveTwoUsers();
    }
}

優點:
- 自動載入上下文,支援 @Autowired/@Resource。
- 可配合 @Transactional 回滾測試資料。
- 避免手動 getBean 字串硬編碼錯誤。

常見坑點

  • component-scan 路徑不包含 Service 類所在包。
  • 多個 applicationContext*.xml 未全部載入 (@ContextConfiguration 需陣列)。
  • 測試類未加 @RunWith,導致 Spring 容器未啟動。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved