Scrivio Interview library
ScenarioIntermediate7 min read · updated 12 November 2026

A codebase uses enum singletons and static singletons for services such as caches and clients. Testing and configuration are painful. What would you propose?

Global singletons hide dependencies, because any class can reach them without declaring it, and they make tests share state, because one instance lives for the whole JVM. We would move caches and clients into dependency injection, for example Spring beans, which are singleton-scoped by default but created, configured and replaced by the container. We refactor gradually: introduce an interface, inject it where it is used, and keep the old singleton as a temporary adapter until no caller needs it. Enum singletons stay only for stateless strategies and true constants, and we remember that Spring's singleton means one instance per container, not per JVM.

Why this question is asked

Many long-lived Java codebases have a CacheManager.INSTANCE or an HttpClients.get() that started as a shortcut and became the backbone of the application. The pain shows up in tests that pass alone and fail together, in configuration that cannot differ between environments without system properties, and in code that is impossible to understand without reading every method body. Interviewers ask this to see whether we can name the real cause and propose a migration a team can actually carry out. In this answer, we will see why global singletons cause these problems, what dependency injection changes, and how to refactor step by step without a big-bang rewrite.

1Why Global Singletons Hurt

A global singleton is an object with one instance reachable from anywhere through a static field, such as an enum constant INSTANCE or a static getInstance() method. The convenience is also the problem. A class that calls PriceCache.INSTANCE.get(...) inside a method depends on the cache, but nothing in its constructor or its fields says so. We only find out by reading the code, and so does every test.

Java
public class QuoteService {
public Money quote(String sku) {
Money cached = PriceCache.INSTANCE.get(sku); // hidden dependency
if (cached != null) return cached;
Money price = PricingClient.getInstance().fetch(sku); // hidden, and talks to a real server
PriceCache.INSTANCE.put(sku, price);
return price;
}
}
// Test 1 puts "sku-1" -> 10.00 into the cache.
// Test 2 expects a fresh fetch for "sku-1", but gets 10.00: state leaked between tests.

The tests show the second problem. The cache lives as long as the JVM, and test runners usually run many test classes in one JVM, so whatever one test leaves behind is visible to the next. The result depends on test order, which is the classic flaky test. Replacing PricingClient with a fake is also awkward, because the code asks a static method for it; we end up with mocking tools that patch static methods, or with setInstanceForTesting() methods that leak test concerns into production code.

Configuration suffers the same way. A singleton creates itself, so it must find its own settings, usually from system properties or a static config class, and two instances with different settings, for example two pricing clients for two regions, are impossible.

2What Dependency Injection Changes

With dependency injection, a class declares what it needs, usually as constructor parameters, and something else, the container, creates the objects and passes them in. In Spring, every bean is singleton-scoped by default, so we still have one PriceCache in the application, but the container owns its lifecycle and every user receives it explicitly.

Java
public interface PriceCache { Money get(String sku); void put(String sku, Money price); }
public interface PricingClient { Money fetch(String sku); }
@Service
public class QuoteService {
private final PriceCache cache;
private final PricingClient client;
public QuoteService(PriceCache cache, PricingClient client) { // dependencies are visible
this.cache = cache;
this.client = client;
}
public Money quote(String sku) { /* same logic, using the fields */ }
}
// Unit test: no Spring, no static state
var service = new QuoteService(new InMemoryPriceCache(), sku -> Money.of("12.50"));
service.quote("sku-1"); // 12.50, each test builds its own fresh objects
Global singleton versus injected bean
Global singletonSpring singleton bean
Dependencies visibleno, hidden in method bodiesyes, in the constructor
Instancesone per class loader, for everone per application context
Test isolationshared state across testsfresh objects or a fresh context
Swap implementationstatic mocking or test hookspass a fake, or @MockitoBean
Configurationthe singleton finds it itselfthe container supplies it

Notice what changed. The constructor documents the dependencies, and the unit test creates fresh objects, so nothing leaks between tests. Configuration moves to the container: a @Bean method or @ConfigurationProperties class builds the PricingClient with the right base URL per environment, and we can define two clients for two regions as two beans.

3Singleton Scope Means One per Container

It is worth being precise about what Spring's singleton means. A singleton bean is one instance per application context, the container, not one per JVM. That is exactly what makes testing easier: each context has its own instances. It also has consequences. Spring's test framework caches contexts and may hold several in one JVM, for example when two test classes use different configurations, so a test must never assume that a bean is the only instance in the JVM. And a class that is both a Spring bean and a static singleton will have two instances, the container's and the static one, which is a frequent bug during migrations.

4Refactoring Gradually

Rewriting every call site at once is risky in a large codebase. Instead, we migrate one dependency at a time, and the old global access keeps working until the last caller has moved.

Java
// Step 1: extract an interface; the old singleton implements it
public enum LegacyPriceCache implements PriceCache {
INSTANCE;
public Money get(String sku) { /* existing code */ }
public void put(String sku, Money price) { /* existing code */ }
}
// Step 2: register the same instance as a bean, so old and new callers share one cache
@Configuration
class CacheConfig {
@Bean PriceCache priceCache() { return LegacyPriceCache.INSTANCE; } // temporary adapter
}
// Step 3: callers move to constructor injection, one class per pull request
// Step 4: when no code references LegacyPriceCache.INSTANCE, replace it with a normal class
Step throughMigrating one singleton
  1. Extract an interfacethe singleton implements it
  2. Expose the same instance as a beanold and new callers share it
  3. Inject the interface, class by classtests use fakes
  4. Block new static referencesArchUnit rule counts them
  5. Any static references left?
    YesContinue migratingNoMake it a plain class owned by the container

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

The key trick is step 2. During the migration, the bean and the global are the same object, so old and new callers see the same cache and nothing behaves differently. That avoids the two-instances bug. Each pull request then moves a few classes to constructor injection, with tests that now use fakes. An architecture test, for example with ArchUnit, counts the remaining references to LegacyPriceCache.INSTANCE and fails if new ones appear, so the number only goes down. When it reaches zero, we turn the enum into an ordinary class built by the container.

5What Stays a Singleton

Not every enum singleton has to go. An enum constant that is stateless and has no configuration, such as a comparator, a parsing strategy or a set of fixed constants, is harmless: it cannot leak state between tests and needs no settings. The rule we would propose is simple. Anything with mutable state, configuration, or an external resource such as a connection, a thread pool or a file is a container-managed bean. Stateless helpers may stay enum singletons or static methods.

6Follow-up questions

Isn't a Spring singleton bean just a global singleton with extra steps?

It has the same instance count inside one application, but the difference is who reaches it and how. Callers receive it through their constructor, so the dependency is visible and replaceable, and the container controls creation, configuration and shutdown. A global is reached from anywhere and controls itself.

How do you test code that still uses a singleton during the migration?

Add a reset method only on the interface implementation used in tests, or clear the shared state in a test hook, and treat these as temporary. The better path is to prioritize migrating the classes whose tests are flakiest.

What about static utility methods?

Pure functions, such as formatting or math helpers, are fine as static methods because they have no state and no dependencies. The problems start when a static method reads configuration or holds a cache.

7Conclusion

In this answer, we saw that global singletons hide dependencies inside method bodies, share state between tests in the same JVM, and must find their own configuration. Dependency injection makes dependencies explicit in constructors and lets the container create, configure and replace them, while Spring's singleton scope still gives one instance per application context. We refactor gradually by extracting an interface, exposing the existing instance as a bean so old and new callers share it, moving callers to injection one by one with a rule that blocks new static references, and keep enum singletons only for stateless helpers and constants.

What to say in the interviewAbout 80 seconds aloud

Open with

The pain comes from the fact that global singletons hide dependencies and share state. A service that calls PriceCache.INSTANCE inside a method depends on it, but its constructor does not say so, tests cannot easily replace it, and because the instance lives for the whole JVM, whatever one test puts into the cache leaks into the next, so tests become order-dependent.

Then, if they want more

Configuration is also awkward, because a singleton has to find its own settings, and you cannot have two differently configured instances. I would move caches and clients into Spring beans.

They are still singletons by default, but per application context, not per JVM, and they are injected through constructors, so dependencies are visible, unit tests can pass fakes, and configuration comes from the container.

I would do it gradually: extract an interface, have the existing singleton implement it, and register that same instance as a bean so old and new callers share one object during the migration.

Then move callers to constructor injection class by class, add an ArchUnit rule so the number of static references only goes down, and finally turn the singleton into a normal class. Enum singletons that are stateless, like strategies or constants, can stay.

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.
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 codebase uses enum singletons and static singletons for services such as caches and...": https://scrivio-interview-library.netlify.app/java/enums/3825560aa4/