Let's consider the following 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!");
}
}
I would expect that first, the class loader loads the class and static functions are called. Then the object is instantiated and spring-boot context loads.
Instated, I see in logs:
...
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v3.0.4)
(...)
hello from static
before all!
I think in Spring Boot 2.7.x it used to work as I expect but after migrating to Spring Boot 3 the outcome is as presented above.
It comes down to the question: how to run any code before Spring Boot starts loading the context?