Scrivio Interview library
CodingFoundations5 min read · updated 12 November 2026

Show three ways to inject a dependency that may not exist, such as an optional MetricsPublisher.

There are three common ways: @Autowired(required = false) on a setter or field, which Spring simply skips if no MetricsPublisher exists; an Optional<MetricsPublisher> constructor parameter, which is empty when the bean is absent; and an ObjectProvider<MetricsPublisher> constructor parameter, where getIfAvailable() returns the bean or null. A constructor parameter annotated with @Nullable is also accepted and receives null when no bean exists.

Why this question is asked

Optional dependencies are everywhere in real code: metrics that only exist in production, an audit publisher that a library may or may not provide, a feature that some deployments switch off. If we inject them like required dependencies, startup fails whenever they are missing. Interviewers ask for several ways because each has a different trade-off in readability, laziness and safety. In this answer, we will recap what happens with a normal injection, then write the same class with each of the three main approaches plus @Nullable, see what each does when the bean is present and when it is missing, and finish with when to choose which.

1A Quick Recap: Required by Default

Spring treats every injection point as required unless we say otherwise. If a class asks for a MetricsPublisher and no bean of that type exists, startup fails with a message that the constructor parameter required a bean of type MetricsPublisher that could not be found. That is usually what we want, because it catches missing configuration early. For a truly optional collaborator, we must tell Spring explicitly that absence is acceptable.

2Way 1: @Autowired(required = false)

The oldest way is to mark a setter or a field as not required. If no matching bean exists, Spring does not call the setter or set the field at all.

Java
@Service
class OrderService {
private MetricsPublisher metrics = MetricsPublisher.NO_OP; // default when absent
@Autowired(required = false)
void setMetrics(MetricsPublisher metrics) { this.metrics = metrics; }
void place(Order o) { metrics.increment("orders.placed"); }
}
// Bean present: setMetrics(...) called, real publisher used
// Bean absent: setter never called, NO_OP used, no error

Notice that combining this with a default value, here a no-op publisher, means the class never has to check for null. The downside is that the dependency is not final and not in the constructor, so it is less visible, and the field can be changed later.

3Way 2: Optional<MetricsPublisher> in the Constructor

Spring understands java.util.Optional at an injection point: it injects Optional.of(bean) when the bean exists and Optional.empty() when it does not.

Java
@Service
class OrderService {
private final MetricsPublisher metrics;
OrderService(Optional<MetricsPublisher> metrics) {
this.metrics = metrics.orElse(MetricsPublisher.NO_OP);
}
}
// Bean present: Optional[RealMetricsPublisher]
// Bean absent: Optional.empty -> NO_OP

The dependency is back in the constructor and the field is final. The resolution happens at construction time, so if the bean exists it is created before OrderService. If there are two MetricsPublisher beans and neither is primary, this still fails with NoUniqueBeanDefinitionException, because Optional means "zero or one", not "any".

4Way 3: ObjectProvider<MetricsPublisher>

ObjectProvider is Spring's own handle for a dependency that we resolve when we choose to. getIfAvailable() returns the bean, or null if there is none.

Java
@Service
class OrderService {
private final ObjectProvider<MetricsPublisher> metrics;
OrderService(ObjectProvider<MetricsPublisher> metrics) { this.metrics = metrics; }
void place(Order o) {
metrics.ifAvailable(m -> m.increment("orders.placed")); // runs only if a bean exists
MetricsPublisher p = metrics.getIfAvailable(() -> MetricsPublisher.NO_OP); // or with a default
}
}
// Bean absent: ifAvailable does nothing, getIfAvailable returns NO_OP
// Two beans, no primary: getIfUnique() returns null instead of failing

The difference from Optional is timing and flexibility. Nothing is looked up at construction; Spring resolves the bean when we call getIfAvailable(), so a bean registered later in startup, or a lazy bean, can still be found. ObjectProvider also has getIfUnique(), which quietly returns null when the choice is ambiguous, and orderedStream() for all candidates. The price is a Spring type in the constructor.

5Also Accepted: @Nullable

Spring also accepts a constructor parameter annotated with a @Nullable annotation: if no bean exists, it passes null instead of failing.

Java
OrderService(@Nullable MetricsPublisher metrics) {
this.metrics = (metrics != null) ? metrics : MetricsPublisher.NO_OP;
}
// Bean absent: metrics is null -> NO_OP
Optional injection: what each way gives us
WayBean absentResolvedNotes
@Autowired(required = false)setter not calledat startuppairs well with a default value
Optional<T> parameterOptional.empty()at constructionfinal field; fails if ambiguous
ObjectProvider<T> parametergetIfAvailable() is nullwhen we call itlazy, getIfUnique, streams
@Nullable parameternullat constructioncompact; handle null at once

Spring recognises any annotation named Nullable, for example JSpecify's org.jspecify.annotations.Nullable, which Spring Framework 7 uses for its own null-safety, or the older Spring and JSR-305 variants (check your version for which ones your code base should standardise on). It is the most compact form, but it brings null back into our code, so we should replace null with a default as soon as possible, as above.

6Follow-up questions

Which one would you use by default?

For a simple optional collaborator in application code, an Optional or @Nullable constructor parameter replaced immediately by a no-op default keeps the class plain and the field final. In libraries and auto-configuration I prefer ObjectProvider, because it resolves lazily and tolerates ambiguity with getIfUnique(), which matters when the library cannot know what the application defines.

Is a no-op default better than checking for null?

Usually, yes. A null object, an implementation that does nothing, lets the rest of the class call metrics.increment() without conditions, so we cannot forget a null check in one method. It is the Null Object pattern, and it keeps the optional part of the design in one place, the constructor.

Does @Autowired(required = false) work on a constructor?

On a constructor it means something different: Spring treats that constructor as one candidate among several and may pick another constructor if it cannot satisfy this one, rather than passing null for the missing argument. For optional constructor arguments, Optional, ObjectProvider or @Nullable are the right tools.

7Conclusion

In this answer, we injected an optional MetricsPublisher in three ways and one more. @Autowired(required = false) on a setter or field skips injection when the bean is absent, ideally paired with a default. An Optional<MetricsPublisher> constructor parameter is empty when absent and keeps the field final. An ObjectProvider<MetricsPublisher> resolves lazily, returning null or a default from getIfAvailable() and offering getIfUnique() for ambiguous cases. A @Nullable parameter is also accepted and receives null. In every case, replacing absence with a no-op default keeps the rest of the class simple.

What to say in the interviewAbout 90 seconds aloud

Open with

By default Spring treats every dependency as required, so for an optional MetricsPublisher I have to say that absence is fine, and there are three common ways. The first is @Autowired with required false on a setter or a field.

Then, if they want more

If there is no bean, Spring just does not call the setter, so I pair it with a field initialised to a no-op publisher. The downside is that the field is not final and the dependency is not in the constructor. The second is a constructor parameter of type Optional of MetricsPublisher.

Spring passes Optional.of the bean or Optional.empty, and I immediately turn it into a final field with orElse of the no-op. It is resolved at construction, and it still fails if there are two candidates without a primary. The third is ObjectProvider of MetricsPublisher.

Nothing is resolved at construction; when I call getIfAvailable, I get the bean or null, or a default if I pass a supplier, and ifAvailable runs code only when the bean exists. It also has getIfUnique for ambiguous cases, which is why I like it in libraries.

Spring also accepts a parameter annotated @Nullable, for example JSpecify's, and passes null when the bean is missing. Whatever I choose, I replace absence with a no-op implementation right away, so the rest of the class never checks for null.

About this answer

Last updated
12 November 2026
Versions it names
Spring Framework 7
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 "Show three ways to inject a dependency that may not exist, such as an optional...": https://scrivio-interview-library.netlify.app/spring-boot/dependency-injection/de4651618d/