DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Smart Dependency Injection With Spring: Assignability (Part 2 of 3)
  • Smart Dependency Injection With Spring: Overview (Part 1 of 3)
  • Smart Dependency Injection With Spring - Generics (Part 3/3)
  • Introduction to Apache Kafka With Spring

Trending

  • DuckDB for Python Developers
  • Replay, Scheduling, and Throttling: Engineering a Self-Service Kafka Streaming Tool at Scale
  • Designing Frontend Applications for Failure, Not Just Success
  • Supercharging AI Agents with Azure Context: A Hands-On Guide to Azure MCP

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Coding
  3. Frameworks
  4. Optional Dependency Injection Using Spring

Optional Dependency Injection Using Spring

Want to learn more about optional dependencies? Click to read more about how to optionally inject dependencies within Spring apps.

By 
Marcos Barbero
·
Updated Jun. 26, 18 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
76.3K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

This guide walks you through the methods available to inject optional dependencies with Spring DI.

Introduction

There are quite a few use cases where it's needed to make some of the dependencies that are injected optional. Here are some example use cases:

  • Provide a default implementation whenever a required infrastructure dependency is not provided, such as DataSources.
  • Prevent the usage of dependencies, such as monitoring, strategies depending on the environment.
  • If you are building your own spring-boot auto-configuration component, sometimes it's necessary to have optional dependencies.

@Autowired

The most know approach to achieve the optional injection is simply to use the @Autowired(required = false). It will look something like this:

@Autowired(required = false)
private HelloService helloService;


Typically, this works fine and gets us to where we wanted to be. However, I don't recommend anyone to use the field injection. One of the reasons for that is the test layer of the application. Whenever field injection is used, it's mandatory to use reflection to inject a different implementation based on the test case.

Java 8 Optional type

You may be familiar with Java 8's Optional type. It can also be used while injecting dependencies with Spring. Here is an example:

@RestController
public class HelloController {

    private Optional<HelloService> optionalHelloService;

    public HelloController(Optional<HelloService> helloService) {
        this.optionalHelloService = helloService;
    }

    @GetMapping("/hello")
    public String hello() {
       return optionalHelloService.map(HelloService::hello)
                .orElse("Hello there, fallback!");
    }
}


The implementation above gives you anOptional monad where you can validate whether the implementation is present before using it.

Spring's ObjectProvider

Since Spring 4.3, there's is a class named ObjectProvider designed specifically for injection points.

According to the javadocs, "a variant of ObjectFactory designed specifically for injection points, allowing for programmatic optionality and lenient not-unique handling."

Using the same example from above:

@RestController
public class HelloController {

    private HelloService helloService;

    public HelloController(ObjectProvider<HelloService> helloServiceProvider) {
        this.helloService = helloServiceProvider.getIfAvailable(DefaultHelloService::new);
    }

    @GetMapping("/hello")
    public String hello() {
        return helloService.hello();
    }

    class DefaultHelloService implements HelloService {

        @Override
        public String hello() {
            return "Hello there, fallback!";
        }
    }
}


In this example, it's not only optional, but it also provides a default implementation as a fallback.

Summary

Congratulations! You just learned a few ways to optionally inject dependencies within Spring apps.

Footnote

  • The code used for this tutorial can be found on GitHub.
  • More about IoC and DI.
Dependency injection Spring Framework

Published at DZone with permission of Marcos Barbero. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Smart Dependency Injection With Spring: Assignability (Part 2 of 3)
  • Smart Dependency Injection With Spring: Overview (Part 1 of 3)
  • Smart Dependency Injection With Spring - Generics (Part 3/3)
  • Introduction to Apache Kafka With Spring

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook