Yanming Zhou opened SPR-17170 and commented
ObjectProvider should accept Function as argument like Consumer #20550
public default <R> Optional<R> ifAvailable(Function<T, R> dependencyFunction) throws BeansException {
T dependency = getIfAvailable();
if (dependency != null) {
return Optional.ofNullable(dependencyFunction.apply(dependency));
}
return Optional.empty();
}
public default <R> Optional<R> ifUnique(Function<T, R> dependencyFunction) throws BeansException {
T dependency = getIfUnique();
if (dependency != null) {
return Optional.ofNullable(dependencyFunction.apply(dependency));
}
return Optional.empty();
}
No further details from SPR-17170
Comment From: spring-projects-issues
Juergen Hoeller commented
For the moment, I have the impression that we got enough overloads in ObjectProvider
for a start. #16046 added iterable/stream access as well, introducing some additional syntactic complexity there. So I'll rather put this ticket into the backlog and see whether we receive feedback about further demand and specific use cases.
Comment From: spring-projects-issues
Yanming Zhou commented
I think mapping is more common used than consuming.
@Autowired
private ObjectProvider<OptionalBean> optionalBeanProvider;
public Optional<String> compute() {
return optionalBeanProvider.applyIfAvailable(bean -> bean.compute());
}
can not write using ifAvailable because it raise compile error.
@Autowired
private ObjectProvider<OptionalBean> optionalBeanProvider;
public Optional<String> compute() {
String result = null;
//Local variable result defined in an enclosing scope must be final or effectively final
optionalBeanProvider.ifAvailable(bean -> result = bean.compute());
return Optional.ofNullable(result);
}
It must introduce some ugly variable holder like AutowiredAnnotationBeanPostProcessorTests.ObjectProviderInjectionBean.consumedTestBean
Comment From: spring-projects-issues
Yanming Zhou commented
In functional world, this is necessary trade-off, CompletableFuture has tons of methods.
Comment From: r-sharath
@quaff , seems like this issue has been fixed in the latest main. Can we close this ?
Comment From: quaff
@r-sharath It's not been fixed, my proposal is accept map function beside consumer function, for now I didn't encounter such requirement in practice, I prefer to close it, but it is migrated by bot not created by me in github, I'm not able to do this, @sbrannen could you close it?