org.springframework.beans.factory.NoSuchBeanDefinitionException:
No bean named 'TestService' is defined
單元測試使用 ClassPathXmlApplicationContext 載入 applicationContext.xml,但該配置檔:
com.zyf.test 包 (context:component-scan 缺失或路徑錯誤)。<bean id="TestService" class="com.zyf.test.TestService"/>。@Service 註解生效需 <context:annotation-config/> + 掃描。<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。
@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 容器未啟動。