ObjectProvider offers ifAvailable/ifUnique variants with Consumer

Issue: SPR-16001
This commit is contained in:
Juergen Hoeller
2017-09-25 22:45:15 +02:00
parent 9ff4c0bff8
commit e927cae476
2 changed files with 62 additions and 1 deletions

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,6 +16,7 @@
package org.springframework.beans.factory;
import java.util.function.Consumer;
import java.util.function.Supplier;
import org.springframework.beans.BeansException;
@@ -68,6 +69,22 @@ public interface ObjectProvider<T> extends ObjectFactory<T> {
return (dependency != null ? dependency : defaultSupplier.get());
}
/**
* Consume an instance (possibly shared or independent) of the object
* managed by this factory, if available.
* @param dependencyConsumer a callback for processing the target object
* if available (not called otherwise)
* @throws BeansException in case of creation errors
* @since 5.0
* @see #getIfAvailable()
*/
default void ifAvailable(Consumer<T> dependencyConsumer) throws BeansException {
T dependency = getIfAvailable();
if (dependency != null) {
dependencyConsumer.accept(dependency);
}
}
/**
* Return an instance (possibly shared or independent) of the object
* managed by this factory.
@@ -96,4 +113,20 @@ public interface ObjectProvider<T> extends ObjectFactory<T> {
return (dependency != null ? dependency : defaultSupplier.get());
}
/**
* Consume an instance (possibly shared or independent) of the object
* managed by this factory, if unique.
* @param dependencyConsumer a callback for processing the target object
* if unique (not called otherwise)
* @throws BeansException in case of creation errors
* @since 5.0
* @see #getIfAvailable()
*/
default void ifUnique(Consumer<T> dependencyConsumer) throws BeansException {
T dependency = getIfUnique();
if (dependency != null) {
dependencyConsumer.accept(dependency);
}
}
}