use of cn.taketoday.beans.BeanWrapperImpl in project today-infrastructure by TAKETODAY.
the class ConstructorResolver method autowireConstructor.
/**
* "autowire constructor" (with constructor arguments by type) behavior.
* Also applied if explicit constructor argument values are specified,
* matching all remaining arguments with beans from the bean factory.
* <p>This corresponds to constructor injection: In this mode, a Framework
* bean factory is able to host components that expect constructor-based
* dependency resolution.
*
* @param beanName the name of the bean
* @param merged the merged bean definition for the bean
* @param chosenCtors chosen candidate constructors (or {@code null} if none)
* @param explicitArgs argument values passed in programmatically via the getBean method,
* or {@code null} if none (-> use constructor argument values from bean definition)
* @return a BeanWrapper for the new instance
*/
public BeanWrapper autowireConstructor(String beanName, RootBeanDefinition merged, @Nullable Constructor<?>[] chosenCtors, @Nullable Object[] explicitArgs) {
BeanWrapperImpl wrapper = new BeanWrapperImpl();
this.beanFactory.initBeanWrapper(wrapper);
Constructor<?> constructorToUse = null;
ArgumentsHolder argsHolderToUse = null;
Object[] argsToUse = null;
if (explicitArgs != null) {
argsToUse = explicitArgs;
} else {
Object[] argsToResolve = null;
synchronized (merged.constructorArgumentLock) {
constructorToUse = (Constructor<?>) merged.resolvedConstructorOrFactoryMethod;
if (constructorToUse != null && merged.constructorArgumentsResolved) {
// Found a cached constructor...
argsToUse = merged.resolvedConstructorArguments;
if (argsToUse == null) {
argsToResolve = merged.preparedConstructorArguments;
}
}
}
if (argsToResolve != null) {
argsToUse = resolvePreparedArguments(beanName, merged, constructorToUse, argsToResolve, wrapper);
}
}
if (constructorToUse == null || argsToUse == null) {
// Take specified constructors, if any.
Constructor<?>[] candidates = chosenCtors;
if (candidates == null) {
Class<?> beanClass = merged.getBeanClass();
try {
candidates = merged.isNonPublicAccessAllowed() ? beanClass.getDeclaredConstructors() : beanClass.getConstructors();
} catch (Throwable ex) {
throw new BeanCreationException(merged.getResourceDescription(), beanName, "Resolution of declared constructors on bean Class [" + beanClass.getName() + "] from ClassLoader [" + beanClass.getClassLoader() + "] failed", ex);
}
}
if (candidates.length == 1 && explicitArgs == null && !merged.hasConstructorArgumentValues()) {
Constructor<?> uniqueCandidate = candidates[0];
if (uniqueCandidate.getParameterCount() == 0) {
synchronized (merged.constructorArgumentLock) {
merged.resolvedConstructorOrFactoryMethod = uniqueCandidate;
merged.constructorArgumentsResolved = true;
merged.resolvedConstructorArguments = EMPTY_ARGS;
}
wrapper.setBeanInstance(instantiate(beanName, merged, uniqueCandidate, EMPTY_ARGS));
return wrapper;
}
}
// Need to resolve the constructor.
boolean autowiring = chosenCtors != null || merged.getResolvedAutowireMode() == AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR;
ConstructorArgumentValues resolvedValues = null;
int minNrOfArgs;
if (explicitArgs != null) {
minNrOfArgs = explicitArgs.length;
} else {
ConstructorArgumentValues cargs = merged.getConstructorArgumentValues();
resolvedValues = new ConstructorArgumentValues();
minNrOfArgs = resolveConstructorArguments(beanName, merged, wrapper, cargs, resolvedValues);
}
AutowireUtils.sortConstructors(candidates);
int minTypeDiffWeight = Integer.MAX_VALUE;
Set<Constructor<?>> ambiguousConstructors = null;
Deque<UnsatisfiedDependencyException> causes = null;
for (Constructor<?> candidate : candidates) {
int parameterCount = candidate.getParameterCount();
if (constructorToUse != null && argsToUse != null && argsToUse.length > parameterCount) {
// do not look any further, there are only less greedy constructors left.
break;
}
if (parameterCount < minNrOfArgs) {
continue;
}
ArgumentsHolder argsHolder;
Class<?>[] paramTypes = candidate.getParameterTypes();
if (resolvedValues != null) {
try {
String[] paramNames = ConstructorPropertiesChecker.evaluate(candidate, parameterCount);
if (paramNames == null) {
ParameterNameDiscoverer pnd = beanFactory.getParameterNameDiscoverer();
if (pnd != null) {
paramNames = pnd.getParameterNames(candidate);
}
}
argsHolder = createArgumentArray(beanName, merged, resolvedValues, paramTypes, paramNames, getUserDeclaredConstructor(candidate), wrapper, autowiring, candidates.length == 1);
} catch (UnsatisfiedDependencyException ex) {
if (log.isTraceEnabled()) {
log.trace("Ignoring constructor [{}] of bean '{}': {}", candidate, beanName, ex);
}
// Swallow and try next constructor.
if (causes == null) {
causes = new ArrayDeque<>(1);
}
causes.add(ex);
continue;
}
} else {
// Explicit arguments given -> arguments length must match exactly.
if (parameterCount != explicitArgs.length) {
continue;
}
argsHolder = new ArgumentsHolder(explicitArgs);
}
int typeDiffWeight = merged.isLenientConstructorResolution() ? argsHolder.getTypeDifferenceWeight(paramTypes) : argsHolder.getAssignabilityWeight(paramTypes);
// Choose this constructor if it represents the closest match.
if (typeDiffWeight < minTypeDiffWeight) {
constructorToUse = candidate;
argsHolderToUse = argsHolder;
argsToUse = argsHolder.arguments;
minTypeDiffWeight = typeDiffWeight;
ambiguousConstructors = null;
} else if (constructorToUse != null && typeDiffWeight == minTypeDiffWeight) {
if (ambiguousConstructors == null) {
ambiguousConstructors = new LinkedHashSet<>();
ambiguousConstructors.add(constructorToUse);
}
ambiguousConstructors.add(candidate);
}
}
if (constructorToUse == null) {
if (causes != null) {
UnsatisfiedDependencyException ex = causes.removeLast();
for (Exception cause : causes) {
beanFactory.onSuppressedException(cause);
}
throw ex;
}
throw new BeanCreationException(merged.getResourceDescription(), beanName, "Could not resolve matching constructor on bean class [" + merged.getBeanClassName() + "] " + "(hint: specify index/type/name arguments for simple parameters to avoid type ambiguities)");
} else if (ambiguousConstructors != null && !merged.isLenientConstructorResolution()) {
throw new BeanCreationException(merged.getResourceDescription(), beanName, "Ambiguous constructor matches found on bean class [" + merged.getBeanClassName() + "] " + "(hint: specify index/type/name arguments for simple parameters to avoid type ambiguities): " + ambiguousConstructors);
}
if (explicitArgs == null && argsHolderToUse != null) {
argsHolderToUse.storeCache(merged, constructorToUse);
}
}
Assert.state(argsToUse != null, "Unresolved constructor arguments");
wrapper.setBeanInstance(instantiate(beanName, merged, constructorToUse, argsToUse));
return wrapper;
}
use of cn.taketoday.beans.BeanWrapperImpl in project today-infrastructure by TAKETODAY.
the class ConstructorResolver method instantiateUsingFactoryMethod.
/**
* Instantiate the bean using a named factory method. The method may be static, if the
* bean definition parameter specifies a class, rather than a "factory-bean", or
* an instance variable on a factory object itself configured using Dependency Injection.
* <p>Implementation requires iterating over the static or instance methods with the
* name specified in the BeanDefinition (the method may be overloaded) and trying
* to match with the parameters. We don't have the types attached to constructor args,
* so trial and error is the only way to go here. The explicitArgs array may contain
* argument values passed in programmatically via the corresponding getBean method.
*
* @param merged the merged bean definition for the bean
* @param explicitArgs argument values passed in programmatically via the getBean
* method, or {@code null} if none (-> use constructor argument values from bean definition)
* @return a BeanWrapper for the new instance
*/
public BeanWrapper instantiateUsingFactoryMethod(String beanName, RootBeanDefinition merged, @Nullable Object[] explicitArgs) {
BeanWrapperImpl wrapper = new BeanWrapperImpl();
beanFactory.initBeanWrapper(wrapper);
boolean isStatic;
Object factoryBean;
Class<?> factoryClass;
String factoryBeanName = merged.getFactoryBeanName();
if (factoryBeanName != null) {
if (factoryBeanName.equals(beanName)) {
throw new BeanDefinitionStoreException(merged.getResourceDescription(), "factory-bean reference points back to the same bean definition");
}
factoryBean = beanFactory.getBean(factoryBeanName);
if (merged.isSingleton() && beanFactory.containsSingleton(beanName)) {
throw new ImplicitlyAppearedSingletonException();
}
beanFactory.registerDependentBean(factoryBeanName, beanName);
factoryClass = factoryBean.getClass();
isStatic = false;
} else {
// It's a static factory method on the bean class.
if (!merged.hasBeanClass()) {
throw new BeanDefinitionStoreException(merged.getResourceDescription(), "bean definition declares neither a bean class nor a factory-bean reference");
}
factoryBean = null;
factoryClass = merged.getBeanClass();
isStatic = true;
}
Method factoryMethodToUse = null;
ArgumentsHolder argsHolderToUse = null;
Object[] argsToUse = null;
if (explicitArgs != null) {
argsToUse = explicitArgs;
} else {
Object[] argsToResolve = null;
synchronized (merged.constructorArgumentLock) {
factoryMethodToUse = (Method) merged.resolvedConstructorOrFactoryMethod;
if (factoryMethodToUse != null && merged.constructorArgumentsResolved) {
// Found a cached factory method...
argsToUse = merged.resolvedConstructorArguments;
if (argsToUse == null) {
argsToResolve = merged.preparedConstructorArguments;
}
}
}
if (argsToResolve != null) {
argsToUse = resolvePreparedArguments(beanName, merged, factoryMethodToUse, argsToResolve, wrapper);
}
}
if (factoryMethodToUse == null || argsToUse == null) {
// Need to determine the factory method...
// Try all methods with this name to see if they match the given arguments.
factoryClass = ClassUtils.getUserClass(factoryClass);
List<Method> candidates = null;
if (merged.isFactoryMethodUnique) {
if (factoryMethodToUse == null) {
factoryMethodToUse = merged.getResolvedFactoryMethod();
}
if (factoryMethodToUse != null) {
candidates = Collections.singletonList(factoryMethodToUse);
}
}
if (candidates == null) {
candidates = new ArrayList<>();
Method[] rawCandidates = getCandidateMethods(factoryClass, merged);
for (Method candidate : rawCandidates) {
if (Modifier.isStatic(candidate.getModifiers()) == isStatic && merged.isFactoryMethod(candidate)) {
candidates.add(candidate);
}
}
}
if (candidates.size() == 1 && explicitArgs == null && !merged.hasConstructorArgumentValues()) {
Method uniqueCandidate = candidates.get(0);
if (uniqueCandidate.getParameterCount() == 0) {
merged.factoryMethodToIntrospect = uniqueCandidate;
synchronized (merged.constructorArgumentLock) {
merged.resolvedConstructorOrFactoryMethod = uniqueCandidate;
merged.constructorArgumentsResolved = true;
merged.resolvedConstructorArguments = EMPTY_ARGS;
}
wrapper.setBeanInstance(instantiate(beanName, merged, factoryBean, uniqueCandidate, EMPTY_ARGS));
return wrapper;
}
}
if (candidates.size() > 1) {
// explicitly skip immutable singletonList
candidates.sort(AutowireUtils.EXECUTABLE_COMPARATOR);
}
ConstructorArgumentValues resolvedValues = null;
boolean autowiring = (merged.getResolvedAutowireMode() == AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR);
int minTypeDiffWeight = Integer.MAX_VALUE;
Set<Method> ambiguousFactoryMethods = null;
int minNrOfArgs;
if (explicitArgs != null) {
minNrOfArgs = explicitArgs.length;
} else {
// arguments specified in the constructor arguments held in the bean definition.
if (merged.hasConstructorArgumentValues()) {
ConstructorArgumentValues cargs = merged.getConstructorArgumentValues();
resolvedValues = new ConstructorArgumentValues();
minNrOfArgs = resolveConstructorArguments(beanName, merged, wrapper, cargs, resolvedValues);
} else {
minNrOfArgs = 0;
}
}
Deque<UnsatisfiedDependencyException> causes = null;
for (Method candidate : candidates) {
int parameterCount = candidate.getParameterCount();
if (parameterCount >= minNrOfArgs) {
ArgumentsHolder argsHolder;
Class<?>[] paramTypes = candidate.getParameterTypes();
if (explicitArgs != null) {
// Explicit arguments given -> arguments length must match exactly.
if (paramTypes.length != explicitArgs.length) {
continue;
}
argsHolder = new ArgumentsHolder(explicitArgs);
} else {
// Resolved constructor arguments: type conversion and/or autowiring necessary.
try {
String[] paramNames = null;
ParameterNameDiscoverer pnd = beanFactory.getParameterNameDiscoverer();
if (pnd != null) {
paramNames = pnd.getParameterNames(candidate);
}
argsHolder = createArgumentArray(beanName, merged, resolvedValues, paramTypes, paramNames, candidate, wrapper, autowiring, candidates.size() == 1);
} catch (UnsatisfiedDependencyException ex) {
if (log.isTraceEnabled()) {
log.trace("Ignoring factory method [{}] of bean '{}': {}", candidate, beanName, ex);
}
// Swallow and try next overloaded factory method.
if (causes == null) {
causes = new ArrayDeque<>(1);
}
causes.add(ex);
continue;
}
}
int typeDiffWeight = merged.isLenientConstructorResolution() ? argsHolder.getTypeDifferenceWeight(paramTypes) : argsHolder.getAssignabilityWeight(paramTypes);
// Choose this factory method if it represents the closest match.
if (typeDiffWeight < minTypeDiffWeight) {
factoryMethodToUse = candidate;
argsHolderToUse = argsHolder;
argsToUse = argsHolder.arguments;
minTypeDiffWeight = typeDiffWeight;
ambiguousFactoryMethods = null;
} else // and explicitly ignore overridden methods (with the same parameter signature).
if (factoryMethodToUse != null && typeDiffWeight == minTypeDiffWeight && !merged.isLenientConstructorResolution() && paramTypes.length == factoryMethodToUse.getParameterCount() && !Arrays.equals(paramTypes, factoryMethodToUse.getParameterTypes())) {
if (ambiguousFactoryMethods == null) {
ambiguousFactoryMethods = new LinkedHashSet<>();
ambiguousFactoryMethods.add(factoryMethodToUse);
}
ambiguousFactoryMethods.add(candidate);
}
}
}
if (factoryMethodToUse == null || argsToUse == null) {
if (causes != null) {
UnsatisfiedDependencyException ex = causes.removeLast();
for (Exception cause : causes) {
beanFactory.onSuppressedException(cause);
}
throw ex;
}
ArrayList<String> argTypes = new ArrayList<>(minNrOfArgs);
if (explicitArgs != null) {
for (Object arg : explicitArgs) {
argTypes.add(arg != null ? arg.getClass().getSimpleName() : "null");
}
} else if (resolvedValues != null) {
LinkedHashSet<ValueHolder> valueHolders = new LinkedHashSet<>(resolvedValues.getArgumentCount());
valueHolders.addAll(resolvedValues.getIndexedArgumentValues().values());
valueHolders.addAll(resolvedValues.getGenericArgumentValues());
for (ValueHolder value : valueHolders) {
String argType = (value.getType() != null ? ClassUtils.getShortName(value.getType()) : (value.getValue() != null ? value.getValue().getClass().getSimpleName() : "null"));
argTypes.add(argType);
}
}
String argDesc = StringUtils.collectionToCommaDelimitedString(argTypes);
throw new BeanCreationException(merged.getResourceDescription(), beanName, "No matching factory method found on class [" + factoryClass.getName() + "]: " + (merged.getFactoryBeanName() != null ? "factory bean '" + merged.getFactoryBeanName() + "'; " : "") + "factory method '" + merged.getFactoryMethodName() + "(" + argDesc + ")'. " + "Check that a method with the specified name " + (minNrOfArgs > 0 ? "and arguments " : "") + "exists and that it is " + (isStatic ? "static" : "non-static") + ".");
} else if (void.class == factoryMethodToUse.getReturnType()) {
throw new BeanCreationException(merged.getResourceDescription(), beanName, "Invalid factory method '" + merged.getFactoryMethodName() + "' on class [" + factoryClass.getName() + "]: needs to have a non-void return type!");
} else if (ambiguousFactoryMethods != null) {
throw new BeanCreationException(merged.getResourceDescription(), beanName, "Ambiguous factory method matches found on class [" + factoryClass.getName() + "] " + "(hint: specify index/type/name arguments for simple parameters to avoid type ambiguities): " + ambiguousFactoryMethods);
}
if (explicitArgs == null && argsHolderToUse != null) {
merged.factoryMethodToIntrospect = factoryMethodToUse;
argsHolderToUse.storeCache(merged, factoryMethodToUse);
}
}
wrapper.setBeanInstance(instantiate(beanName, merged, factoryBean, factoryMethodToUse, argsToUse));
return wrapper;
}
use of cn.taketoday.beans.BeanWrapperImpl in project today-infrastructure by TAKETODAY.
the class CustomEditorTests method testCharacterEditor.
@Test
void testCharacterEditor() {
CharBean cb = new CharBean();
BeanWrapper bw = new BeanWrapperImpl(cb);
bw.setPropertyValue("myChar", Character.valueOf('c'));
assertThat(cb.getMyChar()).isEqualTo('c');
bw.setPropertyValue("myChar", "c");
assertThat(cb.getMyChar()).isEqualTo('c');
bw.setPropertyValue("myChar", "\u0041");
assertThat(cb.getMyChar()).isEqualTo('A');
bw.setPropertyValue("myChar", "\\u0022");
assertThat(cb.getMyChar()).isEqualTo('"');
CharacterEditor editor = new CharacterEditor(false);
editor.setAsText("M");
assertThat(editor.getAsText()).isEqualTo("M");
}
use of cn.taketoday.beans.BeanWrapperImpl in project today-infrastructure by TAKETODAY.
the class CustomEditorTests method testCustomEditorForSingleProperty.
@Test
void testCustomEditorForSingleProperty() {
TestBean tb = new TestBean();
BeanWrapper bw = new BeanWrapperImpl(tb);
bw.registerCustomEditor(String.class, "name", new PropertyEditorSupport() {
@Override
public void setAsText(String text) throws IllegalArgumentException {
setValue("prefix" + text);
}
});
bw.setPropertyValue("name", "value");
bw.setPropertyValue("touchy", "value");
assertThat(bw.getPropertyValue("name")).isEqualTo("prefixvalue");
assertThat(tb.getName()).isEqualTo("prefixvalue");
assertThat(bw.getPropertyValue("touchy")).isEqualTo("value");
assertThat(tb.getTouchy()).isEqualTo("value");
}
use of cn.taketoday.beans.BeanWrapperImpl in project today-infrastructure by TAKETODAY.
the class CustomEditorTests method testComplexObject.
@Test
void testComplexObject() {
TestBean tb = new TestBean();
String newName = "Rod";
String tbString = "Kerry_34";
BeanWrapper bw = new BeanWrapperImpl(tb);
bw.registerCustomEditor(ITestBean.class, new TestBeanEditor());
PropertyValues pvs = new PropertyValues();
pvs.add(new PropertyValue("age", 55));
pvs.add(new PropertyValue("name", newName));
pvs.add(new PropertyValue("touchy", "valid"));
pvs.add(new PropertyValue("spouse", tbString));
bw.setPropertyValues(pvs);
assertThat(tb.getSpouse()).as("spouse is non-null").isNotNull();
assertThat(tb.getSpouse().getName().equals("Kerry") && tb.getSpouse().getAge() == 34).as("spouse name is Kerry and age is 34").isTrue();
}
Aggregations