ObjectProvider offers getIfAvailable/getIfUnique variants with default supplier

Issue: SPR-14980
This commit is contained in:
Juergen Hoeller
2016-12-23 18:49:12 +01:00
parent 54b8aab1c6
commit d3f97e3092
2 changed files with 49 additions and 0 deletions

View File

@@ -16,6 +16,8 @@
package org.springframework.beans.factory;
import java.util.function.Supplier;
import org.springframework.beans.BeansException;
/**
@@ -48,6 +50,22 @@ public interface ObjectProvider<T> extends ObjectFactory<T> {
*/
T getIfAvailable() throws BeansException;
/**
* Return an instance (possibly shared or independent) of the object
* managed by this factory.
* @param defaultSupplier a callback for supplying a default object
* if none is present in the factory
* @return an instance of the bean, or the supplied default object
* if no such bean is available
* @throws BeansException in case of creation errors
* @since 5.0
* @see #getIfAvailable()
*/
default T getIfAvailable(Supplier<T> defaultSupplier) throws BeansException {
T dependency = getIfAvailable();
return (dependency != null ? dependency : defaultSupplier.get());
}
/**
* Return an instance (possibly shared or independent) of the object
* managed by this factory.
@@ -58,4 +76,21 @@ public interface ObjectProvider<T> extends ObjectFactory<T> {
*/
T getIfUnique() throws BeansException;
/**
* Return an instance (possibly shared or independent) of the object
* managed by this factory.
* @param defaultSupplier a callback for supplying a default object
* if no unique candidate is present in the factory
* @return an instance of the bean, or the supplied default object
* if no such bean is available or if it is not unique in the factory
* (i.e. multiple candidates found with none marked as primary)
* @throws BeansException in case of creation errors
* @since 5.0
* @see #getIfUnique()
*/
default T getIfUnique(Supplier<T> defaultSupplier) throws BeansException {
T dependency = getIfUnique();
return (dependency != null ? dependency : defaultSupplier.get());
}
}