Skip to content
javahacks.dev
Architecture

Dependency Inversion in Java and Spring Beyond the Slogan

What the dependency inversion principle means in Java, how it differs from dependency injection and why the interface should belong to the code that uses it.

6 min read
Summarize in AI
Flat illustration of a controller, a service and a repository stacked above a database, with the Spring and Spring Boot logos.

Dependency inversion and dependency injection are routinely confused, and the confusion produces codebases with interfaces everywhere and no inverted dependencies. The principle is a statement about direction, and Spring's container is one way to deliver an implementation. This post separates them and shows what an inverted dependency looks like in a Spring Boot application. The injection mechanics are in what dependency injection really is.

The two halves of the principle

  1. High-level modules should not depend on low-level modules. Both should depend on abstractions.
  2. Abstractions should not depend on details. Details should depend on abstractions.

"High-level" means policy: the business rules. "Low-level" means mechanism: databases, HTTP clients, file formats. The usual dependency flow goes from policy to mechanism, so a change in the mechanism ripples up. Inversion reverses the source-code arrow without changing the runtime call direction.

Without inversion

java
// business logic imports a framework and a vendor SDK
package dev.javahacks.billing;

import com.stripe.Stripe;
import org.springframework.jdbc.core.JdbcTemplate;

class InvoiceService {
    private final JdbcTemplate jdbc;               // concrete, infrastructure
    void charge(Invoice invoice) {
        Stripe.apiKey = "...";
        // call the SDK directly
    }
}

The business class imports the SDK and the database tool. Testing it needs both. Replacing Stripe means editing the business class.

With inversion

The business code defines what it needs, in its own terms:

java
package dev.javahacks.billing;                      // the policy side

public interface PaymentGateway {
    Receipt charge(Money amount, CustomerId customer);
}

public interface InvoiceStore {
    void save(Invoice invoice);
}

class InvoiceService {
    private final PaymentGateway gateway;
    private final InvoiceStore store;
    // constructor injection
}

The implementations live in a different package and depend on the interfaces:

java
package dev.javahacks.billing.infrastructure;       // the detail side

class StripePaymentGateway implements PaymentGateway { /* Stripe SDK */ }
class JdbcInvoiceStore implements InvoiceStore { /* JdbcTemplate */ }

Now the arrow of imports points from infrastructure toward billing, the opposite of the call direction. billing imports nothing from Stripe or Spring JDBC. You can test InvoiceService with in-memory fakes and swap Stripe for another provider by writing one class.

Who owns the interface

The interface must belong to the consumer's package and use the consumer's vocabulary. PaymentGateway.charge(Money, CustomerId) is what billing needs. An interface copied from the vendor SDK (StripeClient) just renames the detail and keeps the dependency. If you find the interface shaped like the implementation, with methods that only make sense for Stripe, it is not inverted.

Injection is the delivery mechanism

Spring wires StripePaymentGateway into InvoiceService:

java
@Configuration
class BillingConfig {
    @Bean
    PaymentGateway paymentGateway() { return new StripePaymentGateway(); }
}

Without a container you could construct them in main. The principle holds either way. A codebase can use injection everywhere and violate inversion (every class injects concrete classes), or satisfy inversion with a manual wiring in main.

An interface with one implementation

UserService and UserServiceImpl, where the interface lives next to the class and nothing else implements it, adds a file and inverts nothing. Introduce an abstraction at an architectural boundary: persistence, external services, messaging, time. Inside a module, depend on concrete classes without apology.

The architecture version

Applied to a whole application, inversion gives ports and adapters: the domain defines ports (interfaces), and adapters implement them for the web, the database and other systems. See hexagonal architecture in Java with Spring Boot. The package rules can be enforced by a test; ArchUnit checks that billing imports nothing from infrastructure:

java
noClasses().that().resideInAPackage("..billing..")
        .should().dependOnClassesThat().resideInAPackage("..infrastructure..");

Make the direction a failing test

Inversion is a rule about which package knows which, and a rule that is not checked drifts. ArchUnit expresses it as a test that runs with the others:

java
@AnalyzeClasses(packages = "dev.javahacks.shop", importOptions = ImportOption.DoNotIncludeTests.class)
class ArchitectureTest {

    @ArchTest
    static final ArchRule domainDoesNotDependOnInfrastructure =
            noClasses().that().resideInAPackage("..domain..")
                       .should().dependOnClassesThat().resideInAnyPackage("..infrastructure..", "org.springframework..", "jakarta.persistence..");

    @ArchTest
    static final ArchRule infrastructureMayDependOnDomain =
            classes().that().resideInAPackage("..infrastructure..")
                     .should().onlyDependOnClassesThat().resideInAnyPackage("..infrastructure..", "..domain..", "java..", "org.springframework..", "jakarta..");
}

The first rule fails the build the day someone imports a Spring annotation into the domain package. The failure message names the class and the dependency, which makes the review short. The stricter first rule is the one that stops framework types from creeping in, and some teams relax it to allow a few annotations.

Spring Modulith does this per module

For an application split into modules, Spring Modulith verifies that modules depend on each other only through their public packages and that there are no cycles. A single test checks the structure:

java
@Test
void verifiesModuleStructure() {
    ApplicationModules.of(ShopApplication.class).verify();
}

It treats each direct sub-package of the application package as a module. Internal types are hidden from other modules, and the dependency graph is checked for cycles. That covers the direction between modules, and ArchUnit rules cover the direction between layers inside one.

A test of the benefit

The practical payoff of inversion is that business rules run with no framework. A rule that depends on an interface owned by the domain runs under a plain lambda in a test:

java
interface Clock2 { Instant now(); }      // owned by the domain, implemented elsewhere

class LateFee {
    private final Clock2 clock;
    LateFee(Clock2 clock) { this.clock = clock; }

    BigDecimal forLoan(Loan loan) {
        long days = Duration.between(loan.dueAt(), clock.now()).toDays();
        return days <= 0 ? BigDecimal.ZERO : new BigDecimal("0.50").multiply(BigDecimal.valueOf(days));
    }
}

@Test
void chargesPerDayLate() {
    LateFee fee = new LateFee(() -> Instant.parse("2026-03-10T00:00:00Z"));
    assertEquals(new BigDecimal("2.50"), fee.forLoan(loanDueOn("2026-03-05T00:00:00Z")));
}

No container, no mock library and no setup. If testing a rule needs a Spring context, the rule depends on the framework, and the dependency points the wrong way.

Signs of a hollow inversion

SignWhat it says
An interface in the same package as its only implementationThe interface is decoration, the dependency still points at the detail
Impl suffix on every classInterfaces are made by habit, with no consumer in mind
The domain imports jakarta.persistenceThe domain depends on the database mapping
A service package imports controller typesThe direction is reversed within the application layer
Tests need @SpringBootTest for a pure ruleThe rule is tied to the container

Fix the first by moving the interface to the package of the code that uses it, or by deleting it. An interface is justified by a consumer that wants to be independent, or by a second implementation, and not by the habit of writing one for each class.

A review habit that keeps the direction honest

Read the imports of the domain package at the start of every code review. A domain class that imports an annotation from a web or persistence package has taken a dependency in the wrong direction, even if the code compiles and the tests pass. The fix is rarely large: move the annotation to an adapter class, or introduce a small interface owned by the domain. The longer the import stays, the more code is written around it, and the more expensive the removal becomes.

Treat the first violation as the important one. A team that allows one framework annotation in the domain finds, a year later, that the domain cannot be compiled without the framework, and that unit tests need a container. The architecture test above makes that first violation visible on the day it happens, when a change of two lines fixes it.

Where the principle costs more than it gives

For a CRUD application whose "business logic" is a few validations, ports and adapters add ceremony with no payoff. Invert dependencies where the detail is likely to change or hard to test, and not by default. SOLID principles in Java puts it in context. The Spring Framework reference on dependency injection and ArchUnit are the primary sources.

Taggedexplainer
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.