ResolvableType-based type matching at the BeanFactory API level

Issue: SPR-12147
This commit is contained in:
Juergen Hoeller
2015-03-18 23:05:13 +01:00
parent a3e5fbf5ed
commit 778a01943b
14 changed files with 323 additions and 102 deletions

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2014 the original author or authors.
* Copyright 2002-2015 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.
@@ -17,6 +17,7 @@
package org.springframework.beans.factory;
import org.springframework.beans.BeansException;
import org.springframework.core.ResolvableType;
/**
* The root interface for accessing a Spring bean container.
@@ -114,6 +115,7 @@ public interface BeanFactory {
*/
String FACTORY_BEAN_PREFIX = "&";
/**
* Return an instance, which may be shared or independent, of the specified bean.
* <p>This method allows a Spring BeanFactory to be used as a replacement for the
@@ -202,6 +204,7 @@ public interface BeanFactory {
*/
<T> T getBean(Class<T> requiredType, Object... args) throws BeansException;
/**
* Does this bean factory contain a bean definition or externally registered singleton
* instance with the given name?
@@ -261,7 +264,24 @@ public interface BeanFactory {
* <p>Translates aliases back to the corresponding canonical bean name.
* Will ask the parent factory if the bean cannot be found in this factory instance.
* @param name the name of the bean to query
* @param targetType the type to match against
* @param targetType the type to match against (as a {@code ResolvableType})
* @return {@code true} if the bean type matches,
* {@code false} if it doesn't match or cannot be determined yet
* @throws NoSuchBeanDefinitionException if there is no bean with the given name
* @since 4.2
* @see #getBean
* @see #getType
*/
boolean isTypeMatch(String name, ResolvableType targetType) throws NoSuchBeanDefinitionException;
/**
* Check whether the bean with the given name matches the specified type.
* More specifically, check whether a {@link #getBean} call for the given name
* would return an object that is assignable to the specified target type.
* <p>Translates aliases back to the corresponding canonical bean name.
* Will ask the parent factory if the bean cannot be found in this factory instance.
* @param name the name of the bean to query
* @param targetType the type to match against (as a {@code Class})
* @return {@code true} if the bean type matches,
* {@code false} if it doesn't match or cannot be determined yet
* @throws NoSuchBeanDefinitionException if there is no bean with the given name

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* Copyright 2002-2015 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,7 +16,6 @@
package org.springframework.beans.factory;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
@@ -24,6 +23,7 @@ import java.util.List;
import java.util.Map;
import org.springframework.beans.BeansException;
import org.springframework.core.ResolvableType;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
@@ -126,6 +126,39 @@ public abstract class BeanFactoryUtils {
return beanNamesForTypeIncludingAncestors(lbf, Object.class);
}
/**
* Get all bean names for the given type, including those defined in ancestor
* factories. Will return unique names in case of overridden bean definitions.
* <p>Does consider objects created by FactoryBeans, which means that FactoryBeans
* will get initialized. If the object created by the FactoryBean doesn't match,
* the raw FactoryBean itself will be matched against the type.
* <p>This version of {@code beanNamesForTypeIncludingAncestors} automatically
* includes prototypes and FactoryBeans.
* @param lbf the bean factory
* @param type the type that beans must match (as a {@code ResolvableType})
* @return the array of matching bean names, or an empty array if none
* @since 4.2
*/
public static String[] beanNamesForTypeIncludingAncestors(ListableBeanFactory lbf, ResolvableType type) {
Assert.notNull(lbf, "ListableBeanFactory must not be null");
String[] result = lbf.getBeanNamesForType(type);
if (lbf instanceof HierarchicalBeanFactory) {
HierarchicalBeanFactory hbf = (HierarchicalBeanFactory) lbf;
if (hbf.getParentBeanFactory() instanceof ListableBeanFactory) {
String[] parentResult = beanNamesForTypeIncludingAncestors(
(ListableBeanFactory) hbf.getParentBeanFactory(), type);
List<String> resultList = new ArrayList<String>();
resultList.addAll(Arrays.asList(result));
for (String beanName : parentResult) {
if (!resultList.contains(beanName) && !hbf.containsLocalBean(beanName)) {
resultList.add(beanName);
}
}
result = StringUtils.toStringArray(resultList);
}
}
return result;
}
/**
* Get all bean names for the given type, including those defined in ancestor
@@ -136,7 +169,7 @@ public abstract class BeanFactoryUtils {
* <p>This version of {@code beanNamesForTypeIncludingAncestors} automatically
* includes prototypes and FactoryBeans.
* @param lbf the bean factory
* @param type the type that beans must match
* @param type the type that beans must match (as a {@code Class})
* @return the array of matching bean names, or an empty array if none
*/
public static String[] beanNamesForTypeIncludingAncestors(ListableBeanFactory lbf, Class<?> type) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* Copyright 2002-2015 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.
@@ -20,6 +20,7 @@ import java.lang.annotation.Annotation;
import java.util.Map;
import org.springframework.beans.BeansException;
import org.springframework.core.ResolvableType;
/**
* Extension of the {@link BeanFactory} interface to be implemented by bean factories
@@ -85,6 +86,34 @@ public interface ListableBeanFactory extends BeanFactory {
*/
String[] getBeanDefinitionNames();
/**
* Return the names of beans matching the given type (including subclasses),
* judging from either bean definitions or the value of {@code getObjectType}
* in the case of FactoryBeans.
* <p><b>NOTE: This method introspects top-level beans only.</b> It does <i>not</i>
* check nested beans which might match the specified type as well.
* <p>Does consider objects created by FactoryBeans, which means that FactoryBeans
* will get initialized. If the object created by the FactoryBean doesn't match,
* the raw FactoryBean itself will be matched against the type.
* <p>Does not consider any hierarchy this factory may participate in.
* Use BeanFactoryUtils' {@code beanNamesForTypeIncludingAncestors}
* to include beans in ancestor factories too.
* <p>Note: Does <i>not</i> ignore singleton beans that have been registered
* by other means than bean definitions.
* <p>This version of {@code getBeanNamesForType} matches all kinds of beans,
* be it singletons, prototypes, or FactoryBeans. In most implementations, the
* result will be the same as for {@code getBeanNamesForType(type, true, true)}.
* <p>Bean names returned by this method should always return bean names <i>in the
* order of definition</i> in the backend configuration, as far as possible.
* @param type the class or interface to match, or {@code null} for all bean names
* @return the names of beans (or objects created by FactoryBeans) matching
* the given object type (including subclasses), or an empty array if none
* @since 4.2
* @see FactoryBean#getObjectType
* @see BeanFactoryUtils#beanNamesForTypeIncludingAncestors(ListableBeanFactory, ResolvableType)
*/
String[] getBeanNamesForType(ResolvableType type);
/**
* Return the names of beans matching the given type (including subclasses),
* judging from either bean definitions or the value of {@code getObjectType}

View File

@@ -68,6 +68,7 @@ import org.springframework.beans.factory.config.InstantiationAwareBeanPostProces
import org.springframework.beans.factory.config.Scope;
import org.springframework.core.DecoratingClassLoader;
import org.springframework.core.NamedThreadLocal;
import org.springframework.core.ResolvableType;
import org.springframework.core.convert.ConversionService;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
@@ -479,9 +480,8 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp
}
@Override
public boolean isTypeMatch(String name, Class<?> targetType) throws NoSuchBeanDefinitionException {
public boolean isTypeMatch(String name, ResolvableType typeToMatch) throws NoSuchBeanDefinitionException {
String beanName = transformedBeanName(name);
Class<?> typeToMatch = (targetType != null ? targetType : Object.class);
// Check manually registered singletons.
Object beanInstance = getSingleton(beanName, false);
@@ -489,15 +489,14 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp
if (beanInstance instanceof FactoryBean) {
if (!BeanFactoryUtils.isFactoryDereference(name)) {
Class<?> type = getTypeForFactoryBean((FactoryBean<?>) beanInstance);
return (type != null && ClassUtils.isAssignable(typeToMatch, type));
return (type != null && typeToMatch.isAssignableFrom(type));
}
else {
return ClassUtils.isAssignableValue(typeToMatch, beanInstance);
return typeToMatch.isInstance(beanInstance);
}
}
else {
return !BeanFactoryUtils.isFactoryDereference(name) &&
ClassUtils.isAssignableValue(typeToMatch, beanInstance);
return (!BeanFactoryUtils.isFactoryDereference(name) && typeToMatch.isInstance(beanInstance));
}
}
else if (containsSingleton(beanName) && !containsBeanDefinition(beanName)) {
@@ -510,14 +509,15 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp
BeanFactory parentBeanFactory = getParentBeanFactory();
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
// No bean definition found in this factory -> delegate to parent.
return parentBeanFactory.isTypeMatch(originalBeanName(name), targetType);
return parentBeanFactory.isTypeMatch(originalBeanName(name), typeToMatch);
}
// Retrieve corresponding bean definition.
RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
Class<?>[] typesToMatch = (FactoryBean.class.equals(typeToMatch) ?
new Class<?>[] {typeToMatch} : new Class<?>[] {FactoryBean.class, typeToMatch});
Class<?> classToMatch = typeToMatch.getRawClass();
Class<?>[] typesToMatch = (FactoryBean.class.equals(classToMatch) ?
new Class<?>[] {classToMatch} : new Class<?>[] {FactoryBean.class, classToMatch});
// Check decorated bean definition, if any: We assume it'll be easier
// to determine the decorated bean's type than the proxy's type.
@@ -559,6 +559,11 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp
}
}
@Override
public boolean isTypeMatch(String name, Class<?> targetType) throws NoSuchBeanDefinitionException {
return isTypeMatch(name, ResolvableType.forClass(targetType));
}
@Override
public Class<?> getType(String name) throws NoSuchBeanDefinitionException {
String beanName = transformedBeanName(name);

View File

@@ -66,6 +66,7 @@ import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.DependencyDescriptor;
import org.springframework.core.OrderComparator;
import org.springframework.core.ResolvableType;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.lang.UsesJava8;
import org.springframework.util.Assert;
@@ -323,7 +324,7 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
//---------------------------------------------------------------------
// Implementation of ListableBeanFactory interface
// Implementation of remaining BeanFactory methods
//---------------------------------------------------------------------
@Override
@@ -372,6 +373,11 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
}
}
//---------------------------------------------------------------------
// Implementation of ListableBeanFactory interface
//---------------------------------------------------------------------
@Override
public boolean containsBeanDefinition(String beanName) {
Assert.notNull(beanName, "Bean name must not be null");
@@ -393,6 +399,11 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
}
}
@Override
public String[] getBeanNamesForType(ResolvableType type) {
return doGetBeanNamesForType(type, true, true);
}
@Override
public String[] getBeanNamesForType(Class<?> type) {
return getBeanNamesForType(type, true, true);
@@ -401,7 +412,8 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
@Override
public String[] getBeanNamesForType(Class<?> type, boolean includeNonSingletons, boolean allowEagerInit) {
if (!isConfigurationFrozen() || type == null || !allowEagerInit) {
return doGetBeanNamesForType(type, includeNonSingletons, allowEagerInit);
return doGetBeanNamesForType(ResolvableType.forClass(type != null ? type : Object.class),
includeNonSingletons, allowEagerInit);
}
Map<Class<?>, String[]> cache =
(includeNonSingletons ? this.allBeanNamesByType : this.singletonBeanNamesByType);
@@ -409,14 +421,14 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
if (resolvedBeanNames != null) {
return resolvedBeanNames;
}
resolvedBeanNames = doGetBeanNamesForType(type, includeNonSingletons, allowEagerInit);
resolvedBeanNames = doGetBeanNamesForType(ResolvableType.forClass(type), includeNonSingletons, allowEagerInit);
if (ClassUtils.isCacheSafe(type, getBeanClassLoader())) {
cache.put(type, resolvedBeanNames);
}
return resolvedBeanNames;
}
private String[] doGetBeanNamesForType(Class<?> type, boolean includeNonSingletons, boolean allowEagerInit) {
private String[] doGetBeanNamesForType(ResolvableType type, boolean includeNonSingletons, boolean allowEagerInit) {
List<String> result = new ArrayList<String>();
// Check all bean definitions.

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2014 the original author or authors.
* Copyright 2002-2015 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.
@@ -33,6 +33,7 @@ import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.NoUniqueBeanDefinitionException;
import org.springframework.beans.factory.SmartFactoryBean;
import org.springframework.core.ResolvableType;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.util.StringUtils;
@@ -167,6 +168,12 @@ public class StaticListableBeanFactory implements ListableBeanFactory {
(bean instanceof FactoryBean && !((FactoryBean<?>) bean).isSingleton()));
}
@Override
public boolean isTypeMatch(String name, ResolvableType targetType) throws NoSuchBeanDefinitionException {
Class<?> type = getType(name);
return (targetType == null || (type != null && targetType.isAssignableFrom(type)));
}
@Override
public boolean isTypeMatch(String name, Class<?> targetType) throws NoSuchBeanDefinitionException {
Class<?> type = getType(name);
@@ -216,22 +223,16 @@ public class StaticListableBeanFactory implements ListableBeanFactory {
}
@Override
public String[] getBeanNamesForType(Class<?> type) {
return getBeanNamesForType(type, true, true);
}
@Override
public String[] getBeanNamesForType(Class<?> type, boolean includeNonSingletons, boolean includeFactoryBeans) {
boolean isFactoryType = (type != null && FactoryBean.class.isAssignableFrom(type));
public String[] getBeanNamesForType(ResolvableType type) {
boolean isFactoryType = (type != null && FactoryBean.class.isAssignableFrom(type.getRawClass()));
List<String> matches = new ArrayList<String>();
for (String name : this.beans.keySet()) {
Object beanInstance = this.beans.get(name);
for (Map.Entry<String, Object> entry : this.beans.entrySet()) {
String name = entry.getKey();
Object beanInstance = entry.getValue();
if (beanInstance instanceof FactoryBean && !isFactoryType) {
if (includeFactoryBeans) {
Class<?> objectType = ((FactoryBean<?>) beanInstance).getObjectType();
if (objectType != null && (type == null || type.isAssignableFrom(objectType))) {
matches.add(name);
}
Class<?> objectType = ((FactoryBean<?>) beanInstance).getObjectType();
if (objectType != null && (type == null || type.isAssignableFrom(objectType))) {
matches.add(name);
}
}
else {
@@ -243,6 +244,16 @@ public class StaticListableBeanFactory implements ListableBeanFactory {
return StringUtils.toStringArray(matches);
}
@Override
public String[] getBeanNamesForType(Class<?> type) {
return getBeanNamesForType(ResolvableType.forClass(type));
}
@Override
public String[] getBeanNamesForType(Class<?> type, boolean includeNonSingletons, boolean allowEagerInit) {
return getBeanNamesForType(ResolvableType.forClass(type));
}
@Override
public <T> Map<String, T> getBeansOfType(Class<T> type) throws BeansException {
return getBeansOfType(type, true, true);
@@ -250,25 +261,23 @@ public class StaticListableBeanFactory implements ListableBeanFactory {
@Override
@SuppressWarnings("unchecked")
public <T> Map<String, T> getBeansOfType(Class<T> type, boolean includeNonSingletons, boolean includeFactoryBeans)
public <T> Map<String, T> getBeansOfType(Class<T> type, boolean includeNonSingletons, boolean allowEagerInit)
throws BeansException {
boolean isFactoryType = (type != null && FactoryBean.class.isAssignableFrom(type));
Map<String, T> matches = new HashMap<String, T>();
for (Map.Entry<String, Object> entry : beans.entrySet()) {
for (Map.Entry<String, Object> entry : this.beans.entrySet()) {
String beanName = entry.getKey();
Object beanInstance = entry.getValue();
// Is bean a FactoryBean?
if (beanInstance instanceof FactoryBean && !isFactoryType) {
if (includeFactoryBeans) {
// Match object created by FactoryBean.
FactoryBean<?> factory = (FactoryBean<?>) beanInstance;
Class<?> objectType = factory.getObjectType();
if ((includeNonSingletons || factory.isSingleton()) &&
objectType != null && (type == null || type.isAssignableFrom(objectType))) {
matches.put(beanName, getBean(beanName, type));
}
// Match object created by FactoryBean.
FactoryBean<?> factory = (FactoryBean<?>) beanInstance;
Class<?> objectType = factory.getObjectType();
if ((includeNonSingletons || factory.isSingleton()) &&
objectType != null && (type == null || type.isAssignableFrom(objectType))) {
matches.put(beanName, getBean(beanName, type));
}
}
else {