在 SpringBootTest 在 spring-boot 3 中加载上下文之前运行代码

sza*_*kal 5 java spring spring-boot spring-boot-test

让我们考虑以下测试:

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class ExampleTest {

    static {
        System.out.println("hello from static");
    }

    @BeforeAll
    static void beforeAll() {
        System.out.println("before all!");
    }

    @Test
    void contextLoads() {
        System.out.println("hello!");
    }
}
Run Code Online (Sandbox Code Playgroud)

我希望类加载器首先加载类并调用静态函数。然后该对象被实例化并加载 spring-boot 上下文。

已声明,我在日志中看到:

...

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v3.0.4)

(...)

hello from static
before all!
Run Code Online (Sandbox Code Playgroud)

我认为在 Spring Boot 2.7.x 中它曾经按我的预期工作,但迁移到 Spring Boot 3 后结果如上所示。

这归结为一个问题:如何在 Spring Boot 开始加载上下文之前运行任何代码?