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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

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

  • Tired of Spring Overhead? Try Dropwizard for Your Next Java Microservice
  • How To Build Resilient Microservices Using Circuit Breakers and Retries: A Developer’s Guide To Surviving
  • Introducing Graph Concepts in Java With Eclipse JNoSQL, Part 3: Understanding Janus
  • Introduction to Retrieval Augmented Generation (RAG)
  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
DZone Core CORE ·
Updated Jun. 26, 18 · Tutorial
Likes (13)
Comment
Save
Tweet
Share
72.7K 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, DZone MVB. 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
Oops! Something Went Wrong

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!