3

I've read some stuff about how auto-configuration works behind the scene (configuration classes with @Conditional, spring.factories inside /META-INF etc...)

Now I'm trying to understand with an example : @JsonTest

I can see this annotation is annotated with things like @AutoConfigureJson

What this @AutoConfigureJson does exactly ? Does it import some configuration classes with beans inside ? How Spring know how to use this annotation (basically this annotation is almost empty and doesn't say which classes to scan)

AntonBoarf
  • 1,239
  • 15
  • 31

1 Answers1

4

@AutoConfigure... (like @AutoConfigureJson) annotations are the way to allow tests with multiple "slices".

Slices load into your tests only a subset of the application, making them run faster. Let's say you need to test a component that uses the Jackson Object Mapper, then you would need the @JsonTest slice. (here is the list of all available slices.)

But you may also need some other part of the framework in your test not just tha single slice; let's say the JPA layer. You may want to annotate the test with both @JsonTest and @DataJpaTest to load both slices. According to the docs, this is not supported.

What you should do instead is choose one of the@...Test annotation, and include the other with an @AutoConfigure... annotation.

@JsonTest
@AutoConfigureDataJpa
class MyTests {
// tests
}

Update: at a certain point while evaluating the annotation, Spring Boot will hit this line and will pass to the method SpringFactoriesLoader.loadFactoryNames() a source, that is the fully qualified name of the annotation (like interface org.springframework.boot.test.autoconfigure.json.AutoConfigureJson for example).

The loadFactoryNames method will do its magic and read the necessary information from here.

If more details are needed, the best thing is to use a debugger and just follow along all the steps.

gere
  • 1,600
  • 1
  • 12
  • 19
  • Ok thank you. But I'm interested about how things work behind the scene. I mean : using @AutoConfigure... is likely to import some classes and beans. How does this work ? How does Spring know which beans or config classes to import ? – AntonBoarf Mar 03 '21 at 16:51
  • 1
    Ok, I have added some more details about that. – gere Mar 03 '21 at 17:52