Scrivio Interview library
ConceptFoundations6 min read · updated 12 November 2026

What does inversion of control mean in Spring, and how is it different from a class creating its own dependencies or using a service locator?

Inversion of control means a class no longer creates or looks up the objects it depends on; the Spring container creates them and hands them over. If a class calls new itself, it is hard-wired to one implementation and hard to test. A service locator removes the new, but the class still asks for its dependencies, which hides them from its API. Spring uses dependency injection, where dependencies arrive through the constructor, setters or fields, and the container also manages lifecycle, scope and proxies.

Why this question is asked

Inversion of control is the idea Spring was built on, and almost every other Spring feature, from transactions to testing, depends on it. Interviewers ask about it early because a candidate who truly understands it can explain why Spring code looks the way it does, why constructor injection is recommended, and why a test can replace a dependency so easily. In this answer, we will start with a class that creates its own dependencies, see what goes wrong, try a service locator, and then move to dependency injection with Spring. Finally, we will look at what else the container takes over once it owns object creation.

1A Quick Recap: What Is Being Inverted?

Every non-trivial class depends on other objects. An OrderService needs a repository to load orders and a payment client to charge cards. Something has to create those objects and connect them. In plain Java, the class that needs a dependency usually does it itself.

Inversion of control, IoC for short, turns that around. The class only says what it needs. Something outside, in Spring's case the container, the ApplicationContext that creates and holds our objects, decides which implementation to use, creates it and passes it in. Control over object creation moves from the class to the container. That is the inversion.

2The Starting Point: A Class That Uses new

Here is the version without any inversion.

Java
public class OrderService {
private final OrderRepository repo = new JdbcOrderRepository("jdbc:postgresql://prod-db/orders");
private final PaymentClient payments = new StripePaymentClient(System.getenv("PAY_KEY"));
public void place(Order o) {
repo.save(o);
payments.charge(o.total());
}
}
// In a unit test:
new OrderService().place(order); // connects to prod-db and calls the real payment API

The class has chosen its own implementations and their configuration. That has three costs. We cannot use a different database or a fake payment client without editing the class. A unit test of place() now needs a real database and real network access. And the connection details are scattered across every class that builds its own objects, instead of living in one place. This is what people mean by hard-wired.

3A Service Locator: Better, but the Class Still Asks

A common first improvement is a service locator, a global registry the class asks for its dependencies. JNDI lookups in old Java EE code worked like this, and so does calling context.getBean() from inside our own classes.

Java
public class OrderService {
public void place(Order o) {
OrderRepository repo = ServiceLocator.get(OrderRepository.class);
PaymentClient payments = ServiceLocator.get(PaymentClient.class);
repo.save(o);
payments.charge(o.total());
}
}
new OrderService(); // compiles fine; nothing says it needs a registry with two entries

The implementation choice has moved out of the class, which helps. But the class is still in control: it reaches out and pulls what it needs. Its constructor does not reveal those needs, so a reader or a test only finds out by reading the method body, or by a failure at runtime when the registry is empty. Every class also depends on the locator itself, a global object that tests must configure and reset.

4Dependency Injection: The Form of IoC Spring Uses

With dependency injection, DI, the class declares its dependencies, usually as constructor parameters, and someone else passes them in. The class neither creates nor looks anything up.

Java
@Service
public class OrderService {
private final OrderRepository repo;
private final PaymentClient payments;
public OrderService(OrderRepository repo, PaymentClient payments) { // the full list of needs
this.repo = repo;
this.payments = payments;
}
public void place(Order o) { repo.save(o); payments.charge(o.total()); }
}
// In a unit test, no Spring at all:
var fakePay = new FakePaymentClient();
new OrderService(new InMemoryOrderRepository(), fakePay).place(order);
System.out.println(fakePay.charges()); // [49.90]
Three ways to get a dependency
ApproachWho chooses the implementation?Visible in the API?Easy to test?
new inside the classthe classnono, needs real resources
service locatorthe registryno, hidden in the codepartly, configure a global
dependency injectionthe container or the calleryes, in the constructoryes, pass fakes

Notice that the dependencies are now part of the API: we cannot create an OrderService without supplying them, and the test passes simple fakes. In the running application, Spring sees that OrderService is a bean, finds beans of type OrderRepository and PaymentClient, and calls the constructor with them. Spring also supports setter injection, for optional dependencies, and field injection with @Autowired, which is shorter but hides dependencies again and needs reflection to fill in tests, so constructor injection is the usual recommendation.

5What Else the Container Takes Over

Once the container creates our objects, it can do more than connect them. It manages lifecycle: it calls initialisation methods such as those marked @PostConstruct after injection and destroy methods at shutdown, which is how a connection pool gets closed. It manages scope: a singleton bean is shared by the whole application, a prototype bean is new each time it is requested, and a request-scoped bean lives for one web request.

Most importantly, it can wrap our objects in proxies, generated objects that stand in front of the real bean and add behaviour. That is how @Transactional opens and commits a transaction, how @Cacheable returns cached results and how method security checks roles. None of this is possible if classes create their dependencies with new, because the container never gets the chance to substitute the wrapped version.

6Follow-up questions

Is IoC the same thing as dependency injection?

Not exactly. IoC is the general principle that a framework, rather than our code, controls some part of the flow, such as creating objects or calling our methods. Dependency injection is one specific form of IoC applied to object creation. Spring uses DI for wiring and other forms of IoC elsewhere, such as calling our event listeners or our controller methods.

Why is constructor injection preferred over field injection?

Constructor injection makes the dependencies required and visible, lets the fields be final, and lets a plain unit test create the object without Spring or reflection. It also exposes design smells: a constructor with ten parameters is a clear sign the class does too much. Field injection hides all of that.

Is calling applicationContext.getBean() inside a service wrong?

It turns the container into a service locator, with the same drawbacks: hidden dependencies and code tied to Spring. It has a few legitimate uses, such as choosing a bean by name at runtime, but even then injecting a Map of beans or an ObjectProvider is usually cleaner.

7Conclusion

In this answer, we saw that inversion of control moves the creation and lookup of dependencies out of a class and into the container. Creating dependencies with new hard-wires implementations and makes testing hard. A service locator removes the new but still makes the class ask, hiding its needs from its API. Dependency injection, the form Spring uses, passes dependencies in through constructors, setters or fields, with constructors preferred. And because the container owns object creation, it can also manage lifecycle, scope and proxies for features such as transactions.

What to say in the interviewAbout 90 seconds aloud

Open with

Inversion of control means my class does not create or look up its dependencies; the container does that and hands them in. In Spring that container is the ApplicationContext.

Then, if they want more

If a class calls new JdbcOrderRepository itself, it is hard-wired to that implementation and its configuration, and a unit test suddenly needs a real database. A service locator, like a JNDI lookup or calling getBean from inside the class, improves things because the implementation choice moves out, but the class still asks for what it needs.

Those needs are hidden in the method body rather than visible in the API, and every class depends on a global registry. Spring uses dependency injection, which is the specific form of IoC where dependencies arrive through the constructor, setters or fields.

I prefer constructor injection, because the dependencies are explicit, the fields can be final and a test can just call the constructor with fakes, no Spring needed.

The other half of the answer is that once the container owns creation, it also manages the lifecycle, like calling @PostConstruct and closing pools at shutdown, the scope, like singleton or request, and it can wrap beans in proxies.

That is how @Transactional, caching and method security work, and none of that would be possible if classes created their own dependencies.

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 "What does inversion of control mean in Spring, and how is it different from a class...": https://scrivio-interview-library.netlify.app/spring-boot/ioc-container/fdebc67bb2/

More in IoC container