知識庫 / Spring / Spring Boot RSS 訂閱

無法找到 @SpringBootConfiguration 與 @DataJpaTest

Spring Boot,Testing
HongKong
14
01:09 PM · Dec 06 ,2025

1. 簡介

在關於 Spring Boot 測試教程中,我們看到了如何使用 @DataJpaTest 註解。

在接下來的教程中,我們將看到 如何解決“Unable to find a @SpringBootConfiguration”錯誤

2. 原因

<em @DataJpaTest</em>> 註解幫助我們設置一個 JPA 測試。為此,它會初始化應用程序,忽略不相關的部分。例如,它會忽略 MVC 控制器。

但是,為了初始化應用程序,它需要配置。

為此,它會在當前包中搜索,並向上遍歷包層次結構,直到找到配置。

例如,讓我們在 <em @DataJpaTest</em>> 中添加 <em com.baeldung.data.jpa</em>> 包,然後它會搜索配置類在:

  • com.baeldung.data.jpa
  • com.baeldung.data
  • 以及其他

但是,如果未找到配置,應用程序將報告錯誤。

Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...)
  with your test java.lang.IllegalStateException

這可能因為配置類位於更具體的包中,例如 com.baeldung.data.jpa.application

讓我們將配置類移動到 com.baeldung.data.jpa。 這樣,Spring 將能夠找到它。

另一方面,我們也可以有一個沒有 @SpringBootConfiguration 的模塊。 在下一部分,我們將探討這種情況。

3. 缺少 <em @SpringBootConfiguration

如果我們的模塊不包含任何 <em @SpringBootConfiguration,可能原因有很多。為了方便演示,我們假設在本教程中,我們的模塊只包含模型類。

因此,解決方案非常簡單。我們只需在測試代碼中添加 <em @SpringBootApplication 即可:

@SpringBootApplication
public class TestApplication {}

現在我們已經擁有了標註的類,Spring 就能啓動我們的測試。

為了驗證我們的配置,讓我們注入一個 TestEntityManager 並驗證它是否已設置:

@RunWith(SpringRunner.class)
@DataJpaTest
public class DataJpaUnitTest {

    @Autowired
    TestEntityManager entityManager;

    @Test
    public void givenACorrectSetup_thenAnEntityManagerWillBeAvailable() {
        assertNotNull(entityManager);
    }
}

這段代碼在 Spring 能夠找到自身包或其父包中定義的 @SpringBootConfiguration 時會成功。

4. 結論在本教程中,我們探討了兩種導致錯誤的可能原因:“無法找到 @SpringBootConfiguration”。

首先,我們考察了配置類無法找到的情況。這是由於其位置不正確造成的。我們通過將配置類移動到另一個位置來解決這個問題。

其次,我們考察了沒有配置類可用的場景。我們通過在測試代碼庫中添加 @SpringBootApplication 來解決這個問題。

user avatar
0 位用戶收藏了這個故事!
收藏

發佈 評論

Some HTML is okay.