教程影片中註解稱 @ContextConfiguration(locations="...") 括號內填「源碼編譯後路徑」,但實際操作卻填入 Spring 配置文件路徑(如 classpath:applicationContext.xml),感到困惑。
Spring 測試框架載入的是 ApplicationContext(容器),而非單純的類路徑。locations 指定的是構建容器所需的配置元數據位置:
classpath:spring/*.xml、file:config/appContext.xmlclasses=AppConfig.class可能指 類路徑根目錄(Maven 預設 target/classes,Gradle 預設 build/classes/java/main),以便用 classpath: 前綴定位資源文件。但實際填寫的是配置文件相對類路徑的路徑,而非 .class 文件本身。
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring/spring-dao.xml", "classpath:spring/spring-service.xml"})
public class ServiceTest { ... }
// Spring Boot 簡化版
@SpringBootTest
public class ServiceTest { ... }
locations 接受資源路徑模式,Spring 會從類路徑/文件系統載入並解析這些配置來構建測試用的 IoC 容器。