Scrivio Interview library
DebuggingIntermediate7 min read · updated 12 November 2026

A test adds a @TestConfiguration that defines a Clock bean to replace the application's Clock, but startup fails with BeanDefinitionOverrideException. Explain why and give three ways to replace the bean correctly.

Spring Boot turns bean definition overriding off by default, so when the test configuration registers a bean with the same name as the application's Clock bean, startup fails instead of silently replacing it. Three correct ways to replace it are a differently named test bean marked @Primary, the @TestBean annotation from Spring Framework 6.2 (or @MockitoBean and @MockitoSpyBean for mocks), and making the application's bean replaceable with @ConditionalOnMissingBean in an auto-configuration or a configurable Clock.

Why this question is asked

Replacing the Clock is one of the most common test needs, because code that reads the current time is otherwise impossible to test deterministically. The BeanDefinitionOverrideException that often greets the first attempt is a deliberate safety feature, and interviewers ask about it to see whether we understand why Spring Boot refuses, and whether we know the modern tools for replacing beans. In this answer, we will reproduce the failure, see why overriding is disabled, go through three correct fixes, and compare how each one affects context caching.

1Reproducing the Failure

The application defines a Clock bean in a configuration class, and the test adds a @TestConfiguration that defines a Clock with the same method name, and therefore the same bean name.

Java
@Configuration
class TimeConfig {
@Bean Clock clock() { return Clock.systemUTC(); } // bean name: clock
}
@SpringBootTest
class InvoiceDueDateTest {
@TestConfiguration
static class FixedTime {
@Bean Clock clock() { // bean name: clock again
return Clock.fixed(Instant.parse("2026-03-01T10:00:00Z"), ZoneOffset.UTC);
}
}
}
// APPLICATION FAILED TO START
// The bean 'clock', defined in class path resource [.../InvoiceDueDateTest$FixedTime.class],
// could not be registered. A bean with that name has already been defined ... and overriding is disabled.

Spring Boot's failure analyzer prints this message with both locations, and the underlying exception is BeanDefinitionOverrideException.

2Why Spring Boot Disables Overriding

In plain Spring Framework, registering a bean definition with an existing name simply replaces the old one. That was convenient, but it also hid real mistakes: two configuration classes that both define dataSource, and whichever one is processed last wins, depending on class loading order. The application starts, but with the wrong bean, and nobody notices until it misbehaves.

So Spring Boot sets spring.main.allow-bean-definition-overriding=false by default. A duplicate name is now an error at startup, which is exactly when we want to know. We could set the property to true in the test, and the error would go away. But that switches the safety off for the whole context, so a real accidental duplicate in the application would also pass silently in our tests. It is better to replace the bean in a way that says clearly what we mean.

3Option 1: A Different Name and @Primary

The simplest fix is to give the test bean its own name and mark it @Primary. Now two Clock beans exist, and @Primary tells Spring which one to inject wherever a single Clock is requested by type.

Java
@TestConfiguration
static class FixedTime {
@Bean @Primary
Clock fixedClock() { // bean name: fixedClock
return Clock.fixed(Instant.parse("2026-03-01T10:00:00Z"), ZoneOffset.UTC);
}
}
// invoiceService.dueDate(order) -> 2026-03-31, computed from the fixed clock

Notice the limits. The original clock bean still exists, so any code that injects it by name, or that collects all Clock beans in a list, still sees it. And if the application already marks its own Clock @Primary, two primary beans fail with NoUniqueBeanDefinitionException. For a normal single-bean injection, though, this works with no framework magic.

4Option 2: @TestBean, @MockitoBean and @MockitoSpyBean

Spring Framework 6.2 added bean override support to the TestContext framework itself. @TestBean on a field in the test class replaces the bean of that type, or of a given name, with the result of a static factory method. By convention the factory method has the same name as the field. The override is applied cleanly, before the context refreshes, so it does not count as a duplicate definition.

Java
@SpringBootTest
class InvoiceDueDateTest {
@TestBean Clock clock; // replaces the Clock bean
static Clock clock() { // factory method, same name as the field
return Clock.fixed(Instant.parse("2026-03-01T10:00:00Z"), ZoneOffset.UTC);
}
@Autowired InvoiceService service;
@Test void dueIn30Days() {
assertThat(service.dueDate(new Order())).isEqualTo(LocalDate.of(2026, 3, 31)); // passes
}
}

For mocks, @MockitoBean replaces a bean with a Mockito mock and @MockitoSpyBean wraps the real bean in a spy. These replace Spring Boot's @MockBean and @SpyBean, which are deprecated since Boot 3.4. The advantage over Option 1 is that there is only one Clock bean in the context, so injection by name, by type and in collections all see the replacement.

5Option 3: Make the Application Bean Replaceable

The third approach changes the application so that replacing the bean is a supported feature. If the Clock is defined in an auto-configuration, the class that Spring Boot loads after user configuration, we annotate it with @ConditionalOnMissingBean. Then any Clock that a test, or another application, defines comes first, and the default simply is not created. This is how Spring Boot's own auto-configurations let us override them.

Notice the catch: @ConditionalOnMissingBean is only reliable in auto-configuration classes, because only those are guaranteed to be processed after user configurations. On a normal @Configuration class the result depends on processing order. Another way to make it replaceable is to inject a configurable Clock, for example one built from a zone property, or to inject an interface such as a TimeSource that tests implement directly.

6How Each Option Affects Context Caching

The context cache key includes every configuration class and every bean override. So all three options create a context that differs from the plain application context. What matters is whether many test classes produce the same key.

Replacing the Clock: costs and caching
OptionBeans of type ClockContext caching
@Primary in nested configtwonew context per distinct nested class
@Primary in shared imported configtwoshared by every class importing it
@TestBean / @MockitoBeanoneshared when the set of overrides is identical
@ConditionalOnMissingBean defaultoneshared when the same test config is used
allow-bean-definition-overriding=trueone, silentlya new context, and hides real mistakes
Put the replacement in one shared place so many test classes reuse one context.

So with nested configurations, every test class gets its own context, even if the nested classes are identical copies. With @TestBean or @MockitoBean declared the same way, for example in a shared base class or meta-annotation, the classes share one cached context. A mock bean whose behaviour each test configures is still one context, since the cache key depends on the declaration, not on the stubbing.

7Follow-up questions

How does each option affect context caching?

Each option changes the cache key, so a test using it does not share the context of tests without it. Nested @Primary configurations give one context per test class because each nested class is a different key. A shared imported configuration, or identical @TestBean or @MockitoBean declarations in a common base class, give one context for all classes that use them. Turning overriding on with a property also changes the key and makes the tests less trustworthy.

Why not just use Clock.fixed in a constructor in unit tests?

For plain unit tests, we should: create the service with new and pass a fixed Clock, no Spring needed. The bean replacement question only arises in integration tests where Spring wires the service, and there we want the whole context to see the same fixed clock.

What if I need the time to move during the test?

Use a mutable test clock, a small Clock subclass with an advance(Duration) method, and register it with @TestBean or as a @Primary bean. The test then moves time forward between steps, for example to check that an invoice becomes overdue after 30 days.

8Conclusion

In this answer, we saw that the BeanDefinitionOverrideException appears because Spring Boot disables bean definition overriding, so a second bean named clock is an error rather than a silent replacement. We replaced the bean correctly with a differently named @Primary bean, with @TestBean or @MockitoBean from Spring Framework 6.2, or by making the application bean replaceable with @ConditionalOnMissingBean in an auto-configuration. We avoided turning overriding on globally, and we saw that keeping replacements in one shared place keeps the context cache effective.

What to say in the interviewAbout 80 seconds aloud

Open with

The test bean and the application bean both have the name clock, because the bean name comes from the method name, and Spring Boot sets allow-bean-definition-overriding to false by default.

Then, if they want more

So instead of letting the last definition win silently, which used to hide real wiring mistakes, it fails at startup with a BeanDefinitionOverrideException. I would not set the property to true, because that hides accidental duplicates in the application too. There are three clean ways to replace it.

First, give the test bean a different name, like fixedClock, and mark it Primary, so injection by type picks it; the original bean still exists, which is fine for most code.

Second, on Spring Framework 6.2 and later, use TestBean on a field with a static factory method of the same name, or MockitoBean and MockitoSpyBean for mocks; these replace the bean definition before refresh, so there is exactly one Clock. Third, make the application's Clock replaceable, with ConditionalOnMissingBean in an auto-configuration or by injecting a configurable time source.

For caching, each override changes the context key, so I put the replacement in one shared place, an imported config or a common base class, so many test classes reuse one context instead of each starting its own.

About this answer

Last updated
12 November 2026
Versions it names
Spring Framework 6
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 "A test adds a @TestConfiguration that defines a Clock bean to replace the application's...": https://scrivio-interview-library.netlify.app/spring-boot/spring-boot-test/c67e0cd1fb/