I write a library on spring-boot and it is used by multiple apps.
Since it is a library, I do not know what beans are defined up front; thus I use ObjectProvider
often.
Currently, to check whether the beans are not unique(with semantics of @Primary
is the unique), we need to use List or iterate and check the size.
To streamline the API, it is nice to have getIfNotUnique
and its variant methods available in ObjectProvider
.
Something like:
- List<T> getIfNotUnique()
- List<T> getIfNotUnique(Supplier<List<T>> defaultSupplier)
- void ifNotUnique(Consumer<List<T>> consumer)
If ordering is the matter, may need to separate APIs for ordered and not ordered.
Comment From: sdeleuze
Aren't stream()
and orderedStream()
(potentially used in combination with collect(Collectors.toList())
) good enough for this kind of use cases?
Comment From: ttddyy
Yes, it is possible to achieve with existing APIs, but I feel it is nice if ObjectProvider
provides more enrich APIs. For this case, analogous to ifAvailable
or ifUnique
and their variants; so that, the programming style can be unified.
Similar to https://github.com/spring-projects/spring-framework/issues/23774, the more I use ObjectProvider
, the better if it had more APIs covering usage patterns.
Comment From: ttddyy
For implementation side, if it only scratch API surface with default method, it would be something like:
default void ifNotUnique(Consumer<List<T>> consumer) {
List<T> list = stream().collect(Collectors.toList());
if (list.size() > 1) {
consumer.accept(list);
}
}
If it goes to bean factory reusing existing impl:
@Nullable
private Stream<T> notUniqueStream() {
String[] beanNames = getBeanNamesForTypedStream(requiredType);
Set<T> matchingBeans = new HashSet<>(beanNames.length);
for (String beanName : beanNames) {
Object beanInstance = getBean(beanName);
if (!(beanInstance instanceof NullBean)) {
matchingBeans.add((T) beanInstance);
}
}
if (matchingBeans.size() < 2) {
return null;
}
return matchingBeans.stream();
}
Or, if supporting from bottom implementation,
DefaultListableBeanFactory#resolveNamedBean
may need to allow returning list of beans...
Comment From: snicoll
Thanks for the suggestion but I don't think adding ifNotUnique
variant is warranted for such API, especially when you can achieve the same goal using the existing method.