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
Over 2 million developers have joined DZone.
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

  • Optimizing High-Volume REST APIs Using Redis Caching and Spring Boot (With Load Testing Code)
  • Feature Flag Debt: Performance Impact in Enterprise Applications
  • LLM-Powered Deep Parsing for Industrial Inventory Search
  • OpenAPI From Code With Spring and Java: A Recipe for Your CI
  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 user avatar
Marcos Barbero
·
Updated Jun. 26, 18 · Tutorial
Likes (13)
Comment
Save
Tweet
Share
75.6K Views

Join the DZone community and get the full member experience.

Join For Free

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

The likes didn't load as expected. Please refresh the page and try again.

  • 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