springboot: Component scanning

By default a SpringbootApplication annotation will implicitly enable automatic component scanning in the current package and all descendants. That can be a problem if certain items should not be used for all invocations of the application. You can control which components are discovered in a few different ways:

In tests it can be useful to override the real application items. One way to do that is via a custom TestConfiguration with @Primary beans (don't forget to mark DirtiesContext because by default tests can share the expensive to construct Springboot context):

@SpringBootTest
@Import(SpecialConfig::class, etc.)
@DirtiesContext
class Foo {}

@TestConfiguration
class SpecialConfig {
    @Bean @Primary
    fun foo(): SomeType = ...
}
Published on: 20 Mar 2024