Issue
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?
Solution
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.
Answered By - João Dias