Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve bean qualifiers #9778

Merged
merged 2 commits into from
Aug 28, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
113 changes: 66 additions & 47 deletions inject/src/main/java/io/micronaut/context/DefaultBeanContext.java
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@
import io.micronaut.inject.provider.AbstractProviderDefinition;
import io.micronaut.inject.proxy.InterceptedBeanProxy;
import io.micronaut.inject.qualifiers.AnyQualifier;
import io.micronaut.inject.qualifiers.FilteringQualifier;
import io.micronaut.inject.qualifiers.Qualified;
import io.micronaut.inject.qualifiers.Qualifiers;
import io.micronaut.inject.validation.BeanDefinitionValidator;
Expand All @@ -132,6 +133,7 @@
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
Expand Down Expand Up @@ -793,7 +795,7 @@ public <T> Collection<BeanDefinition<T>> getBeanDefinitions(Argument<T> beanType
Objects.requireNonNull(beanType, "Bean type cannot be null");
Collection<BeanDefinition<T>> candidates = findBeanCandidatesInternal(null, beanType);
if (qualifier != null) {
candidates = qualifier.reduce(beanType.getType(), candidates.stream()).toList();
candidates = qualifier.filter(beanType.getType(), candidates);
}
return Collections.unmodifiableCollection(candidates);
}
Expand Down Expand Up @@ -1531,25 +1533,46 @@ public Collection<BeanDefinition<?>> getBeanDefinitions(@Nullable Qualifier<Obje
LOG.debug("Finding candidate beans for qualifier: {}", qualifier);
}
// first traverse component definition classes and load candidates
Collection candidates;
if (!beanDefinitionsClasses.isEmpty()) {
Stream<BeanDefinitionReference> reduced = qualifier.reduce(Object.class, beanDefinitionsClasses.stream()
.filter(p -> p.isReferenceEnabled(this))
.map(BeanDefinitionProducer::getReference));
Stream<BeanDefinition> candidateStream = qualifier.reduce(Object.class,
reduced
.map(ref -> ref.load(this))
.filter(candidate -> candidate.isEnabled(this))
if (beanDefinitionsClasses.isEmpty()) {
return Collections.emptyList();
}
Collection<BeanDefinition<Object>> candidates;
if (qualifier instanceof FilteringQualifier<Object> filteringQualifier) {
List<BeanDefinition<Object>> bdCandidates = new ArrayList<>(20);
for (BeanDefinitionProducer producer : beanDefinitionsClasses) {
if (!producer.isReferenceEnabled(this)) {
continue;
}
BeanDefinitionReference<Object> reference = producer.getReference();
if (!filteringQualifier.isQualifies(Object.class, reference)) {
continue;
}
BeanDefinition<Object> beanDefinition = reference.load(this);
if (!beanDefinition.isEnabled(this)) {
continue;
}
if (!filteringQualifier.isQualifies(Object.class, beanDefinition)) {
continue;
}
bdCandidates.add(beanDefinition);
}
candidates = bdCandidates;
} else {
Stream<BeanDefinitionReference<Object>> reduced = qualifier.reduce(Object.class, beanDefinitionsClasses.stream()
.filter(p -> p.isReferenceEnabled(this))
.map(BeanDefinitionProducer::getReference));
Stream<BeanDefinition<Object>> candidateStream = qualifier.reduce(Object.class,
reduced
.map(ref -> ref.load(this))
.filter(candidate -> candidate.isEnabled(this))
);
candidates = candidateStream.collect(Collectors.toList());

} else {
return Collections.emptyList();
}
if (CollectionUtils.isNotEmpty(candidates)) {

if (!candidates.isEmpty()) {
filterReplacedBeans(null, candidates);
}
return candidates;
return (Collection) candidates;
}

@SuppressWarnings("unchecked")
Expand Down Expand Up @@ -2588,16 +2611,14 @@ private <T> boolean qualifiedByQualifier(BeanDefinition<T> definitionToBeReplace
@SuppressWarnings("unchecked") final Class<? extends Annotation> qualifierClass =
(Class<? extends Annotation>) qualifier.getType().orElse(null);
if (qualifierClass != null && !qualifierClass.isAssignableFrom(Annotation.class)) {
return Qualifiers.<T>byStereotype(qualifierClass).qualify(replacedBeanType, Stream.of(definitionToBeReplaced))
.isPresent();
return Qualifiers.<T>byStereotype(qualifierClass).isQualifies(replacedBeanType, definitionToBeReplaced);
} else {
throw new ConfigurationException(String.format("Default qualifier value was used while replacing %s", replacedBeanType));
}
}

private <T> boolean qualifiedByNamed(BeanType<T> definitionToBeReplaced, Class replacedBeanType, String named) {
return Qualifiers.<T>byName(named).qualify(replacedBeanType, Stream.of(definitionToBeReplaced))
.isPresent();
private <T> boolean qualifiedByNamed(BeanType<T> definitionToBeReplaced, Class<T> replacedBeanType, String named) {
return Qualifiers.<T>byName(named).isQualifies(replacedBeanType, definitionToBeReplaced);
}

private <T> Class<T> getCanonicalBeanType(BeanDefinition<T> beanDefinition) {
Expand Down Expand Up @@ -2808,17 +2829,15 @@ protected <T> String resolveDisabledBeanMessage(BeanResolutionContext resolutio

if (disabledMessage == null) {

Set<BeanDefinition<T>> beanDefinitions = collectBeanCandidates(
Collection<BeanDefinition<T>> beanDefinitions = collectBeanCandidates(
resolutionContext,
beanType,
false,
null,
disabledBeans.values()
);
if (qualifier != null) {
beanDefinitions = qualifier
.reduce(beanType.getType(), beanDefinitions.stream())
.collect(Collectors.toSet());
beanDefinitions = qualifier.filter(beanType.getType(), beanDefinitions);
}

if (!beanDefinitions.isEmpty()) {
Expand Down Expand Up @@ -3143,8 +3162,7 @@ private <T> Optional<BeanDefinition<T>> pickOneBean(
LOG.debug("Qualifying bean [{}] for qualifier: {} ", beanType.getName(), qualifier);
}

Stream<BeanDefinition<T>> qualified = qualifier.reduce(beanType.getType(), candidates.stream());
List<BeanDefinition<T>> beanDefinitionList = qualified.toList();
Collection<BeanDefinition<T>> beanDefinitionList = qualifier.filter(beanType.getType(), candidates);
if (beanDefinitionList.isEmpty()) {
if (LOG.isDebugEnabled()) {
LOG.debug("No qualifying beans of type [{}] found for qualifier: {} ", beanType.getName(), qualifier);
Expand Down Expand Up @@ -3416,11 +3434,10 @@ public <T> Collection<BeanRegistration<T>> getBeanRegistrations(@Nullable BeanRe

Collection<BeanDefinition<T>> beanDefinitions = findBeanCandidatesInternal(resolutionContext, beanType);
if (!beanDefinitions.isEmpty()) {
Stream<BeanDefinition<T>> candidateStream = applyBeanResolutionFilters(resolutionContext, beanDefinitions.stream());
beanDefinitions = applyBeanResolutionFilters(resolutionContext, beanDefinitions);
if (qualifier != null) {
candidateStream = qualifier.reduce(beanType.getType(), candidateStream);
beanDefinitions = qualifier.filter(beanType.getType(), beanDefinitions);
}
beanDefinitions = candidateStream.toList();
}

Collection<BeanRegistration<T>> beanRegistrations;
Expand Down Expand Up @@ -3472,7 +3489,7 @@ private <T> Collection<BeanRegistration<T>> resolveBeanRegistrations(BeanResolut
}
addCandidateToList(resolutionContext, definition, beanType, qualifier, beansOfTypeList);
}
if (beansOfTypeList != Collections.EMPTY_SET) {
if (!beansOfTypeList.isEmpty()) {
if (Ordered.class.isAssignableFrom(beanType.getType())) {
return beansOfTypeList.stream().sorted(OrderUtil.COMPARATOR).toList();
}
Expand All @@ -3493,22 +3510,26 @@ private <T> void logResolvedExistingBeanRegistrations(Argument<T> beanType, Qual
}
}

private <T> Stream<BeanDefinition<T>> applyBeanResolutionFilters(@Nullable BeanResolutionContext resolutionContext, Stream<BeanDefinition<T>> candidateStream) {
private <T> Collection<BeanDefinition<T>> applyBeanResolutionFilters(@Nullable BeanResolutionContext resolutionContext, Collection<BeanDefinition<T>> candidates) {
BeanResolutionContext.Segment<?, ?> segment = resolutionContext != null ? resolutionContext.getPath().peek() : null;
BeanDefinition<?> declaringBean = null;
Class<?> proxyTargetDefinitionType = null;
if (segment instanceof AbstractBeanResolutionContext.ConstructorSegment || segment instanceof AbstractBeanResolutionContext.MethodSegment) {
BeanDefinition<?> declaringBean = segment.getDeclaringType();
declaringBean = segment.getDeclaringType();
// if the currently injected segment is a constructor argument and the type to be constructed is the
// same as the candidate, then filter out the candidate to avoid a circular injection problem
candidateStream = candidateStream.filter(c -> {
if (c.equals(declaringBean)) {
return false;
} else if (declaringBean instanceof ProxyBeanDefinition<?> proxyBeanDefinition) {
return !proxyBeanDefinition.getTargetDefinitionType().equals(c.getClass());
}
return true;
});
if (declaringBean instanceof ProxyBeanDefinition<?> proxyBeanDefinition) {
proxyTargetDefinitionType = proxyBeanDefinition.getTargetDefinitionType();
}
}
candidates = new LinkedHashSet<>(candidates); // Make mutable
for (Iterator<BeanDefinition<T>> iterator = candidates.iterator(); iterator.hasNext(); ) {
BeanDefinition<T> c = iterator.next();
if (c.isAbstract() || declaringBean != null && c.equals(declaringBean) || proxyTargetDefinitionType != null && proxyTargetDefinitionType.equals(c.getClass())) {
iterator.remove();
}
}
return candidateStream.filter(c -> !c.isAbstract());
return candidates;
}

private <T> void addCandidateToList(@Nullable BeanResolutionContext resolutionContext,
Expand All @@ -3534,8 +3555,7 @@ private <T> void addCandidateToList(@Nullable BeanResolutionContext resolutionCo
if (container instanceof Object[] array) {
container = Arrays.asList(array);
}
if (container instanceof Iterable) {
Iterable<Object> iterable = (Iterable<Object>) container;
if (container instanceof Iterable<?> iterable) {
int i = 0;
for (Object o : iterable) {
if (o == null || !beanType.isInstance(o)) {
Expand All @@ -3559,11 +3579,10 @@ private <T> boolean isCandidatePresent(Argument<T> beanType, Qualifier<T> qualif
final Collection<BeanDefinition<T>> candidates = findBeanCandidates(null, beanType, true, null);
if (!candidates.isEmpty()) {
filterReplacedBeans(null, candidates);
Stream<BeanDefinition<T>> stream = candidates.stream();
if (qualifier != null && !(qualifier instanceof AnyQualifier)) {
stream = qualifier.reduce(beanType.getType(), stream);
if (qualifier != null) {
return qualifier.isQualifies(beanType.getType(), candidates);
}
return stream.findAny().isPresent();
return true;
}
return false;
}
Expand Down
38 changes: 38 additions & 0 deletions inject/src/main/java/io/micronaut/context/Qualifier.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import io.micronaut.context.annotation.Primary;
import io.micronaut.inject.BeanType;

import java.util.Collection;
import java.util.Optional;
import java.util.stream.Stream;

Expand Down Expand Up @@ -65,4 +66,41 @@ default boolean contains(Qualifier<T> qualifier) {
default <BT extends BeanType<T>> Optional<BT> qualify(Class<T> beanType, Stream<BT> candidates) {
return reduce(beanType, candidates).findFirst();
}

/**
* Check if the candidate qualifies.
*
* @param beanType The bean type
* @param candidate The candidate
* @return true if matches
* @since 4.2.0
*/
default boolean isQualifies(Class<T> beanType, BeanType<T> candidate) {
yawkat marked this conversation as resolved.
Show resolved Hide resolved
return reduce(beanType, Stream.of(candidate)).findAny().isPresent();
}

/**
* Check if at least one candidate qualifies.
*
* @param beanType The bean type
* @param candidates The candidates
* @return true if qualifies
* @since 4.2.0
*/
default boolean isQualifies(Class<T> beanType, Collection<? extends BeanType<T>> candidates) {
return reduce(beanType, candidates.stream()).findAny().isPresent();
}

/**
* Filter the candidates.
*
* @param beanType The bean type
* @param candidates The candidates
* @param <BT> The bean type subclass
* @return The filtered candidates
* @since 4.2.0
*/
default <BT extends BeanType<T>> Collection<BT> filter(Class<T> beanType, Collection<BT> candidates) {
return reduce(beanType, candidates.stream()).toList();
}
}
5 changes: 2 additions & 3 deletions inject/src/main/java/io/micronaut/context/SingletonScope.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Stream;

/**
* The singleton scope implementation.
Expand Down Expand Up @@ -146,8 +145,8 @@ Collection<BeanRegistration> getBeanRegistrations() {
Collection<BeanRegistration<?>> getBeanRegistrations(@NonNull Qualifier<?> qualifier) {
List<BeanRegistration<?>> beanRegistrations = new ArrayList<>();
for (BeanRegistration<?> beanRegistration : singletonByBeanDefinition.values()) {
BeanDefinition beanDefinition = beanRegistration.beanDefinition;
if (qualifier.reduce(beanDefinition.getBeanType(), Stream.of(beanDefinition)).findFirst().isPresent()) {
BeanDefinition<Object> beanDefinition = (BeanDefinition<Object>) beanRegistration.beanDefinition;
if (((Qualifier<Object>) qualifier).isQualifies(beanDefinition.getBeanType(), beanDefinition)) {
beanRegistrations.add(beanRegistration);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
* A {@link io.micronaut.context.Qualifier} that uses {@link AnnotationMetadata}.
Expand All @@ -48,7 +47,7 @@
* @since 1.0
*/
@Internal
final class AnnotationMetadataQualifier<T> implements Qualifier<T> {
final class AnnotationMetadataQualifier<T> extends FilteringQualifier<T> {

@NonNull
final String annotationName;
Expand Down Expand Up @@ -93,30 +92,27 @@ static <T extends Annotation> AnnotationMetadataQualifier<T> fromValue(@NonNull
}

@Override
public <BT extends BeanType<T>> Stream<BT> reduce(Class<T> beanType, Stream<BT> candidates) {
return candidates.filter(candidate -> {
if (!QualifierUtils.matchType(beanType, candidate)) {
return false;
}
if (QualifierUtils.matchAny(beanType, candidate)) {
public boolean isQualifies(Class<T> beanType, BeanType<T> candidate) {
if (!QualifierUtils.matchType(beanType, candidate)) {
return false;
}
if (QualifierUtils.matchAny(beanType, candidate)) {
return true;
}
if (candidate instanceof BeanDefinition<T> bdCandidate) {
Qualifier<T> candidateDeclaredQualifier = bdCandidate.getDeclaredQualifier();
if (candidateDeclaredQualifier != null && candidateDeclaredQualifier.contains(this)) {
return true;
}
if (candidate instanceof BeanDefinition) {
BeanDefinition<T> bdCandidate = (BeanDefinition<T>) candidate;
Qualifier<T> candidateDeclaredQualifier = bdCandidate.getDeclaredQualifier();
if (candidateDeclaredQualifier != null && candidateDeclaredQualifier.contains(this)) {
if (candidate instanceof DelegatingBeanDefinition) {
if (matchByAnnotationMetadata(candidate)) {
return true;
}
if (candidate instanceof DelegatingBeanDefinition) {
if (matchByAnnotationMetadata(candidate)) {
return true;
}
}
} else if (matchByAnnotationMetadata(candidate)) {
return true;
}
return QualifierUtils.matchByCandidateName(candidate, beanType, annotationSimpleName);
});
} else if (matchByAnnotationMetadata(candidate)) {
return true;
}
return QualifierUtils.matchByCandidateName(candidate, beanType, annotationSimpleName);
}

private <BT extends BeanType<T>> boolean matchByAnnotationMetadata(BT candidate) {
Expand Down
Loading