Scrivio Interview library
DesignIntermediate6 min read · updated 12 November 2026

Your team wants a custom test slice for Kafka listeners that loads only the listener beans and Kafka infrastructure. How are Spring Boot slices built, and would you build one?

A Spring Boot slice is an annotation that combines a TypeExcludeFilter, which decides which of our component classes are scanned, with an @ImportAutoConfiguration list of auto-configurations read from an imports file named after the annotation. A custom Kafka slice would add a filter that keeps only listener beans and an imports file listing Kafka's auto-configuration. I would build one only if many tests need it; otherwise @SpringBootTest(classes = ...) with a focused configuration and a Testcontainers Kafka broker with @ServiceConnection is simpler.

Why this question is asked

Teams with many Kafka listeners often find that testing them through @SpringBootTest starts the whole application, including web, security and every other integration, just to check that a message is consumed correctly. A slice that loads only listeners and Kafka sounds ideal. Interviewers ask this to see whether we understand how Boot's slices are built and, as importantly, whether we can judge when custom test infrastructure is worth its upkeep. In this answer, we will look inside a built-in slice, build a Kafka listener slice step by step, compare it with a simpler alternative, and decide.

1How the Built-In Slices Work

Every built-in slice, such as @WebMvcTest or @DataJpaTest, is a composed annotation, an annotation that carries other annotations. Looking at one, we find the same pieces. @BootstrapWith picks the test context bootstrapper, which finds our @SpringBootConfiguration and builds the test context. @ExtendWith(SpringExtension.class) connects it to JUnit. @OverrideAutoConfiguration(enabled = false) switches off normal auto-configuration. @TypeExcludeFilters names a filter class that rejects every scanned class except the types the slice wants. And @ImportAutoConfiguration brings back only the auto-configurations the slice needs.

The list for @ImportAutoConfiguration is not written in Java. Boot reads it from a file on the classpath, META-INF/spring/ followed by the annotation's fully qualified name and .imports, with one auto-configuration class per line. That is how a slice stays in step with Boot's own auto-configurations.

Step throughHow a slice builds its context
  1. Bootstrapper finds @SpringBootConfigurationour application class
  2. Component scan runsTypeExcludeFilter rejects other types
  3. Normal auto-configuration is off@OverrideAutoConfiguration(enabled = false)
  4. Imports file is readonly the listed auto-configurations apply
  5. Context startssmall, one layer

5 steps in order. Play them, or step through them one at a time.

2Building a Kafka Listener Slice

Following the same pattern, our slice is an annotation, a filter and an imports file. The exact base classes and auto-configuration names have changed between Boot versions, especially with the modular packages in Boot 4, so check your version before copying the names.

Java
@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited
@BootstrapWith(SpringBootTestContextBootstrapper.class)
@ExtendWith(SpringExtension.class)
@OverrideAutoConfiguration(enabled = false)
@TypeExcludeFilters(KafkaListenerTypeExcludeFilter.class)
@ImportAutoConfiguration // reads the imports file named after this annotation
public @interface KafkaListenerTest { }
class KafkaListenerTypeExcludeFilter extends TypeExcludeFilter {
@Override
public boolean match(MetadataReader reader, MetadataReaderFactory factory) {
// true means "exclude": keep only classes with @KafkaListener methods
return !reader.getAnnotationMetadata().hasAnnotatedMethods(KafkaListener.class.getName());
}
@Override public boolean equals(Object o) { return o != null && o.getClass() == getClass(); }
@Override public int hashCode() { return getClass().hashCode(); }
}
# src/test/resources/META-INF/spring/com.example.test.KafkaListenerTest.imports
org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration

Notice the equals and hashCode on the filter. The filter becomes part of the test context's cache key, so without them every test class would get its own context and the slice would be slower than expected. Notice also that the filter keeps only listener classes; whatever those listeners call, such as a service, is left out, and tests must mock it with @MockitoBean, just as with @WebMvcTest.

3Using It With a Real Broker

A listener slice is most useful against a real broker, because the behaviour we want to check, deserialization, error handling, retries and offsets, lives there. Testcontainers starts Kafka in a container and @ServiceConnection tells Boot its address, so the listener connects without any properties.

Java
@KafkaListenerTest
@Testcontainers
class PaymentListenerTest {
@Container @ServiceConnection
static KafkaContainer kafka = new KafkaContainer("apache/kafka:4.0.0");
@MockitoBean LedgerService ledger; // the listener's dependency
@Autowired KafkaTemplate<String, String> template;
@Test
void recordsPayment() {
template.send("payments", "p-1", "{"amount":100}");
verify(ledger, timeout(5000)).record("p-1", 100); // passes once the listener consumed it
}
}

The KafkaContainer class and image name depend on the Testcontainers version, so check your version. The test sends a real message and waits, up to 5 seconds, for the mocked service to be called by the listener.

4The Simpler Alternative

Before building a slice, consider @SpringBootTest(classes = ...) with a small configuration that lists exactly what a test needs. Pointing classes at a test configuration rather than the application class means only those beans and the auto-configurations they trigger are loaded.

Java
@SpringBootTest(classes = PaymentListenerTestConfig.class)
class PaymentListenerFocusedTest { /* same test body */ }
@Configuration
@ImportAutoConfiguration(KafkaAutoConfiguration.class)
@Import(PaymentListener.class)
class PaymentListenerTestConfig { }

This needs no filter, no imports file and nothing to maintain across Boot upgrades. Its cost is that each listener's tests repeat a little configuration, and each different configuration is a separate cached context.

5Would We Build One?

I would build the slice only if many tests across services share the need: for example, a platform team supporting 30 services that are mostly Kafka consumers. Then the slice saves real time and gives everyone the same, correct setup. If it is one team with a few listeners, the focused configuration is cheaper.

If we do build it, it becomes a small product: it lives in the shared test library, has documentation and an example test, and has an owner who updates it with each Boot upgrade, because the filter base classes and auto-configuration names can move between versions, as they did in Boot 4.

Custom slice versus focused configuration
AspectCustom @KafkaListenerTest@SpringBootTest(classes = ...)
Setup per testOne annotationA small configuration class
MaintenanceFilter and imports file across upgradesAlmost none
Consistency across teamsHighDepends on each team
Worth it whenMany tests, many servicesA few tests, one team

6Follow-up questions

Why does the filter need equals and hashCode?

Context customizers, including the slice's type exclude filters, form part of the context cache key. Two instances of a filter without equals would never be equal, so every test class would miss the cache and start a new context.

Could we use the existing spring-kafka EmbeddedKafka instead of Testcontainers?

Yes, @EmbeddedKafka starts an in-process broker and is quick. A container runs the same Kafka version as production, which matters for features and configuration, and @ServiceConnection removes the property wiring. Many teams use embedded Kafka for speed and containers for the integration layer.

How do you document a custom slice?

With a short page saying what it loads, what it leaves out and which beans tests must mock, plus one example test in the shared library that runs on every build, so a Boot upgrade that breaks the slice fails there first.

7Conclusion

In this answer, we saw that a slice is a composed annotation with a bootstrapper, a TypeExcludeFilter that limits scanning, disabled normal auto-configuration and an imports file listing the auto-configurations to apply. We built a Kafka listener slice that way and used it with a Testcontainers broker and @ServiceConnection, compared it with @SpringBootTest(classes = ...) and a focused configuration, and decided to build the slice only when many tests share the need, with documentation and an owner for upgrades.

What to say in the interviewAbout 80 seconds aloud

Open with

Boot's slices are composed annotations. They use a bootstrapper and the Spring extension, turn off normal auto-configuration with @OverrideAutoConfiguration, add a TypeExcludeFilter that rejects every scanned class except the types the slice wants, and use @ImportAutoConfiguration, which reads a file in META-INF/spring named after the annotation, listing the auto-configurations to apply.

Then, if they want more

So a Kafka listener slice would be an annotation with those pieces, a filter that keeps only classes with @KafkaListener methods, with equals and hashCode so the context cache still works, and an imports file listing Kafka's auto-configuration. The exact base classes and names moved in Boot 4, so I would check the version.

Tests would mock what the listeners call and run against a real broker from Testcontainers with @ServiceConnection. Would I build it? Only if many tests across services need it, for example a platform with dozens of consumer services.

For one team, @SpringBootTest with classes pointing at a small configuration that imports the Kafka auto-configuration and the listener does the same job with nothing to maintain. If we did build the slice, I would put it in the shared test library with docs, an example test and an owner who keeps it working across Boot upgrades.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
Spring Boot reference, Testing
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Your team wants a custom test slice for Kafka listeners that loads only the listener...": https://scrivio-interview-library.netlify.app/spring-boot/spring-boot-test/41317d0ea9/