user6412004
user6412004

Reputation:

How to handle optional service dependency of service in Spring Boot?

I've a service called InformationService. It optionally depends on ReleaseService. If the property external.releaseservice.url is set, the InformationService shall make a request to it and enrich it's own response with aggregate data.
If however the url is not defined, the response shall simply return a string like not available for the fields in question.

What's the spring boot way to achieve this? Inject an Optional<ReleaseService> into the InformationService? Is there another pattern for this?

Upvotes: 1

Views: 2787

Answers (1)

Jo&#227;o Dias
Jo&#227;o Dias

Reputation: 17510

You have three ways to achieve this.

@Autowired(required = false)

This works, but it requires field injection, which is not great for unit tests as is well known.

@Autowired(required = false)
private ReleaseService releaseService;

Java Optional type

As you said, Optional will also do the job and it allows you to stick to constructor injection. This is my suggested approach.

Spring's ObjectProvider

There is also an ObjectProvider designed specifically for injection points which you can use to achieve this as follows.

public InformationService(ObjectProvider<ReleaseService> releaseServiceProvider) {
    this.releaseService = releaseServiceProvider.getIfAvailable();
}

It is more cumbersome and therefore I would avoid it. There is an advantage that allows you to specify a default instance if none is available but I guess that is not what you need.

Upvotes: 1

Related Questions