Search in sources :

Example 36 with ConstructorArgumentValues

use of org.springframework.beans.factory.config.ConstructorArgumentValues in project spring-boot by spring-projects.

the class AutoConfigurationPackages method register.

/**
	 * Programmatically registers the auto-configuration package names. Subsequent
	 * invocations will add the given package names to those that have already been
	 * registered. You can use this method to manually define the base packages that will
	 * be used for a given {@link BeanDefinitionRegistry}. Generally it's recommended that
	 * you don't call this method directly, but instead rely on the default convention
	 * where the package name is set from your {@code @EnableAutoConfiguration}
	 * configuration class or classes.
	 * @param registry the bean definition registry
	 * @param packageNames the package names to set
	 */
public static void register(BeanDefinitionRegistry registry, String... packageNames) {
    if (registry.containsBeanDefinition(BEAN)) {
        BeanDefinition beanDefinition = registry.getBeanDefinition(BEAN);
        ConstructorArgumentValues constructorArguments = beanDefinition.getConstructorArgumentValues();
        constructorArguments.addIndexedArgumentValue(0, addBasePackages(constructorArguments, packageNames));
    } else {
        GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
        beanDefinition.setBeanClass(BasePackages.class);
        beanDefinition.getConstructorArgumentValues().addIndexedArgumentValue(0, packageNames);
        beanDefinition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
        registry.registerBeanDefinition(BEAN, beanDefinition);
    }
}
Also used : GenericBeanDefinition(org.springframework.beans.factory.support.GenericBeanDefinition) GenericBeanDefinition(org.springframework.beans.factory.support.GenericBeanDefinition) BeanDefinition(org.springframework.beans.factory.config.BeanDefinition) ConstructorArgumentValues(org.springframework.beans.factory.config.ConstructorArgumentValues)

Example 37 with ConstructorArgumentValues

use of org.springframework.beans.factory.config.ConstructorArgumentValues in project spring-boot by spring-projects.

the class EndpointMBeanExporterTests method registerLoggersEndpoint.

private MBeanExporter registerLoggersEndpoint() {
    this.context = new GenericApplicationContext();
    this.context.registerBeanDefinition("endpointMbeanExporter", new RootBeanDefinition(EndpointMBeanExporter.class));
    RootBeanDefinition bd = new RootBeanDefinition(LoggersEndpoint.class);
    ConstructorArgumentValues values = new ConstructorArgumentValues();
    values.addIndexedArgumentValue(0, new LogbackLoggingSystem(getClass().getClassLoader()));
    bd.setConstructorArgumentValues(values);
    this.context.registerBeanDefinition("loggersEndpoint", bd);
    this.context.refresh();
    return this.context.getBean(EndpointMBeanExporter.class);
}
Also used : GenericApplicationContext(org.springframework.context.support.GenericApplicationContext) RootBeanDefinition(org.springframework.beans.factory.support.RootBeanDefinition) LogbackLoggingSystem(org.springframework.boot.logging.logback.LogbackLoggingSystem) ConstructorArgumentValues(org.springframework.beans.factory.config.ConstructorArgumentValues)

Example 38 with ConstructorArgumentValues

use of org.springframework.beans.factory.config.ConstructorArgumentValues in project spring-framework by spring-projects.

the class ConfigBeanDefinitionParser method createAdviceDefinition.

/**
	 * Creates the RootBeanDefinition for a POJO advice bean. Also causes pointcut
	 * parsing to occur so that the pointcut may be associate with the advice bean.
	 * This same pointcut is also configured as the pointcut for the enclosing
	 * Advisor definition using the supplied MutablePropertyValues.
	 */
private AbstractBeanDefinition createAdviceDefinition(Element adviceElement, ParserContext parserContext, String aspectName, int order, RootBeanDefinition methodDef, RootBeanDefinition aspectFactoryDef, List<BeanDefinition> beanDefinitions, List<BeanReference> beanReferences) {
    RootBeanDefinition adviceDefinition = new RootBeanDefinition(getAdviceClass(adviceElement, parserContext));
    adviceDefinition.setSource(parserContext.extractSource(adviceElement));
    adviceDefinition.getPropertyValues().add(ASPECT_NAME_PROPERTY, aspectName);
    adviceDefinition.getPropertyValues().add(DECLARATION_ORDER_PROPERTY, order);
    if (adviceElement.hasAttribute(RETURNING)) {
        adviceDefinition.getPropertyValues().add(RETURNING_PROPERTY, adviceElement.getAttribute(RETURNING));
    }
    if (adviceElement.hasAttribute(THROWING)) {
        adviceDefinition.getPropertyValues().add(THROWING_PROPERTY, adviceElement.getAttribute(THROWING));
    }
    if (adviceElement.hasAttribute(ARG_NAMES)) {
        adviceDefinition.getPropertyValues().add(ARG_NAMES_PROPERTY, adviceElement.getAttribute(ARG_NAMES));
    }
    ConstructorArgumentValues cav = adviceDefinition.getConstructorArgumentValues();
    cav.addIndexedArgumentValue(METHOD_INDEX, methodDef);
    Object pointcut = parsePointcutProperty(adviceElement, parserContext);
    if (pointcut instanceof BeanDefinition) {
        cav.addIndexedArgumentValue(POINTCUT_INDEX, pointcut);
        beanDefinitions.add((BeanDefinition) pointcut);
    } else if (pointcut instanceof String) {
        RuntimeBeanReference pointcutRef = new RuntimeBeanReference((String) pointcut);
        cav.addIndexedArgumentValue(POINTCUT_INDEX, pointcutRef);
        beanReferences.add(pointcutRef);
    }
    cav.addIndexedArgumentValue(ASPECT_INSTANCE_FACTORY_INDEX, aspectFactoryDef);
    return adviceDefinition;
}
Also used : RootBeanDefinition(org.springframework.beans.factory.support.RootBeanDefinition) RootBeanDefinition(org.springframework.beans.factory.support.RootBeanDefinition) AbstractBeanDefinition(org.springframework.beans.factory.support.AbstractBeanDefinition) BeanDefinition(org.springframework.beans.factory.config.BeanDefinition) RuntimeBeanReference(org.springframework.beans.factory.config.RuntimeBeanReference) ConstructorArgumentValues(org.springframework.beans.factory.config.ConstructorArgumentValues)

Example 39 with ConstructorArgumentValues

use of org.springframework.beans.factory.config.ConstructorArgumentValues in project spring-framework by spring-projects.

the class PropertiesBeanDefinitionReader method registerBeanDefinition.

/**
	 * Get all property values, given a prefix (which will be stripped)
	 * and add the bean they define to the factory with the given name
	 * @param beanName name of the bean to define
	 * @param map Map containing string pairs
	 * @param prefix prefix of each entry, which will be stripped
	 * @param resourceDescription description of the resource that the
	 * Map came from (for logging purposes)
	 * @throws BeansException if the bean definition could not be parsed or registered
	 */
protected void registerBeanDefinition(String beanName, Map<?, ?> map, String prefix, String resourceDescription) throws BeansException {
    String className = null;
    String parent = null;
    String scope = GenericBeanDefinition.SCOPE_SINGLETON;
    boolean isAbstract = false;
    boolean lazyInit = false;
    ConstructorArgumentValues cas = new ConstructorArgumentValues();
    MutablePropertyValues pvs = new MutablePropertyValues();
    for (Map.Entry<?, ?> entry : map.entrySet()) {
        String key = StringUtils.trimWhitespace((String) entry.getKey());
        if (key.startsWith(prefix + SEPARATOR)) {
            String property = key.substring(prefix.length() + SEPARATOR.length());
            if (CLASS_KEY.equals(property)) {
                className = StringUtils.trimWhitespace((String) entry.getValue());
            } else if (PARENT_KEY.equals(property)) {
                parent = StringUtils.trimWhitespace((String) entry.getValue());
            } else if (ABSTRACT_KEY.equals(property)) {
                String val = StringUtils.trimWhitespace((String) entry.getValue());
                isAbstract = TRUE_VALUE.equals(val);
            } else if (SCOPE_KEY.equals(property)) {
                // Spring 2.0 style
                scope = StringUtils.trimWhitespace((String) entry.getValue());
            } else if (SINGLETON_KEY.equals(property)) {
                // Spring 1.2 style
                String val = StringUtils.trimWhitespace((String) entry.getValue());
                scope = ((val == null || TRUE_VALUE.equals(val) ? GenericBeanDefinition.SCOPE_SINGLETON : GenericBeanDefinition.SCOPE_PROTOTYPE));
            } else if (LAZY_INIT_KEY.equals(property)) {
                String val = StringUtils.trimWhitespace((String) entry.getValue());
                lazyInit = TRUE_VALUE.equals(val);
            } else if (property.startsWith(CONSTRUCTOR_ARG_PREFIX)) {
                if (property.endsWith(REF_SUFFIX)) {
                    int index = Integer.parseInt(property.substring(1, property.length() - REF_SUFFIX.length()));
                    cas.addIndexedArgumentValue(index, new RuntimeBeanReference(entry.getValue().toString()));
                } else {
                    int index = Integer.parseInt(property.substring(1));
                    cas.addIndexedArgumentValue(index, readValue(entry));
                }
            } else if (property.endsWith(REF_SUFFIX)) {
                // This isn't a real property, but a reference to another prototype
                // Extract property name: property is of form dog(ref)
                property = property.substring(0, property.length() - REF_SUFFIX.length());
                String ref = StringUtils.trimWhitespace((String) entry.getValue());
                // It doesn't matter if the referenced bean hasn't yet been registered:
                // this will ensure that the reference is resolved at runtime.
                Object val = new RuntimeBeanReference(ref);
                pvs.add(property, val);
            } else {
                // It's a normal bean property.
                pvs.add(property, readValue(entry));
            }
        }
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Registering bean definition for bean name '" + beanName + "' with " + pvs);
    }
    // backwards compatibility reasons.
    if (parent == null && className == null && !beanName.equals(this.defaultParentBean)) {
        parent = this.defaultParentBean;
    }
    try {
        AbstractBeanDefinition bd = BeanDefinitionReaderUtils.createBeanDefinition(parent, className, getBeanClassLoader());
        bd.setScope(scope);
        bd.setAbstract(isAbstract);
        bd.setLazyInit(lazyInit);
        bd.setConstructorArgumentValues(cas);
        bd.setPropertyValues(pvs);
        getRegistry().registerBeanDefinition(beanName, bd);
    } catch (ClassNotFoundException ex) {
        throw new CannotLoadBeanClassException(resourceDescription, beanName, className, ex);
    } catch (LinkageError err) {
        throw new CannotLoadBeanClassException(resourceDescription, beanName, className, err);
    }
}
Also used : ConstructorArgumentValues(org.springframework.beans.factory.config.ConstructorArgumentValues) MutablePropertyValues(org.springframework.beans.MutablePropertyValues) CannotLoadBeanClassException(org.springframework.beans.factory.CannotLoadBeanClassException) RuntimeBeanReference(org.springframework.beans.factory.config.RuntimeBeanReference) HashMap(java.util.HashMap) Map(java.util.Map)

Example 40 with ConstructorArgumentValues

use of org.springframework.beans.factory.config.ConstructorArgumentValues in project spring-framework by spring-projects.

the class ConstructorResolver method createArgumentArray.

/**
	 * Create an array of arguments to invoke a constructor or factory method,
	 * given the resolved constructor argument values.
	 */
private ArgumentsHolder createArgumentArray(String beanName, RootBeanDefinition mbd, ConstructorArgumentValues resolvedValues, BeanWrapper bw, Class<?>[] paramTypes, String[] paramNames, Executable executable, boolean autowiring) throws UnsatisfiedDependencyException {
    TypeConverter customConverter = this.beanFactory.getCustomTypeConverter();
    TypeConverter converter = (customConverter != null ? customConverter : bw);
    ArgumentsHolder args = new ArgumentsHolder(paramTypes.length);
    Set<ConstructorArgumentValues.ValueHolder> usedValueHolders = new HashSet<>(paramTypes.length);
    Set<String> autowiredBeanNames = new LinkedHashSet<>(4);
    for (int paramIndex = 0; paramIndex < paramTypes.length; paramIndex++) {
        Class<?> paramType = paramTypes[paramIndex];
        String paramName = (paramNames != null ? paramNames[paramIndex] : "");
        // Try to find matching constructor argument value, either indexed or generic.
        ConstructorArgumentValues.ValueHolder valueHolder = resolvedValues.getArgumentValue(paramIndex, paramType, paramName, usedValueHolders);
        // it could match after type conversion (for example, String -> int).
        if (valueHolder == null && (!autowiring || paramTypes.length == resolvedValues.getArgumentCount())) {
            valueHolder = resolvedValues.getGenericArgumentValue(null, null, usedValueHolders);
        }
        if (valueHolder != null) {
            // We found a potential match - let's give it a try.
            // Do not consider the same value definition multiple times!
            usedValueHolders.add(valueHolder);
            Object originalValue = valueHolder.getValue();
            Object convertedValue;
            if (valueHolder.isConverted()) {
                convertedValue = valueHolder.getConvertedValue();
                args.preparedArguments[paramIndex] = convertedValue;
            } else {
                ConstructorArgumentValues.ValueHolder sourceHolder = (ConstructorArgumentValues.ValueHolder) valueHolder.getSource();
                Object sourceValue = sourceHolder.getValue();
                MethodParameter methodParam = MethodParameter.forExecutable(executable, paramIndex);
                try {
                    convertedValue = converter.convertIfNecessary(originalValue, paramType, methodParam);
                    // TODO re-enable once race condition has been found (SPR-7423)
                    /*
						if (originalValue == sourceValue || sourceValue instanceof TypedStringValue) {
							// Either a converted value or still the original one: store converted value.
							sourceHolder.setConvertedValue(convertedValue);
							args.preparedArguments[paramIndex] = convertedValue;
						}
						else {
						*/
                    args.resolveNecessary = true;
                    args.preparedArguments[paramIndex] = sourceValue;
                // }
                } catch (TypeMismatchException ex) {
                    throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, new InjectionPoint(methodParam), "Could not convert argument value of type [" + ObjectUtils.nullSafeClassName(valueHolder.getValue()) + "] to required type [" + paramType.getName() + "]: " + ex.getMessage());
                }
            }
            args.arguments[paramIndex] = convertedValue;
            args.rawArguments[paramIndex] = originalValue;
        } else {
            MethodParameter methodParam = MethodParameter.forExecutable(executable, paramIndex);
            // have to fail creating an argument array for the given constructor.
            if (!autowiring) {
                throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, new InjectionPoint(methodParam), "Ambiguous argument values for parameter of type [" + paramType.getName() + "] - did you specify the correct bean references as arguments?");
            }
            try {
                Object autowiredArgument = resolveAutowiredArgument(methodParam, beanName, autowiredBeanNames, converter);
                args.rawArguments[paramIndex] = autowiredArgument;
                args.arguments[paramIndex] = autowiredArgument;
                args.preparedArguments[paramIndex] = new AutowiredArgumentMarker();
                args.resolveNecessary = true;
            } catch (BeansException ex) {
                throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, new InjectionPoint(methodParam), ex);
            }
        }
    }
    for (String autowiredBeanName : autowiredBeanNames) {
        this.beanFactory.registerDependentBean(autowiredBeanName, beanName);
        if (this.beanFactory.logger.isDebugEnabled()) {
            this.beanFactory.logger.debug("Autowiring by type from bean name '" + beanName + "' via " + (executable instanceof Constructor ? "constructor" : "factory method") + " to bean named '" + autowiredBeanName + "'");
        }
    }
    return args;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) InjectionPoint(org.springframework.beans.factory.InjectionPoint) Constructor(java.lang.reflect.Constructor) TypeMismatchException(org.springframework.beans.TypeMismatchException) ValueHolder(org.springframework.beans.factory.config.ConstructorArgumentValues.ValueHolder) ValueHolder(org.springframework.beans.factory.config.ConstructorArgumentValues.ValueHolder) InjectionPoint(org.springframework.beans.factory.InjectionPoint) ConstructorArgumentValues(org.springframework.beans.factory.config.ConstructorArgumentValues) TypeConverter(org.springframework.beans.TypeConverter) UnsatisfiedDependencyException(org.springframework.beans.factory.UnsatisfiedDependencyException) MethodParameter(org.springframework.core.MethodParameter) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) BeansException(org.springframework.beans.BeansException)

Aggregations

ConstructorArgumentValues (org.springframework.beans.factory.config.ConstructorArgumentValues)96 Test (org.junit.Test)63 GenericApplicationContext (org.springframework.context.support.GenericApplicationContext)50 BeanCreationException (org.springframework.beans.factory.BeanCreationException)23 RootBeanDefinition (org.springframework.beans.factory.support.RootBeanDefinition)20 RuntimeBeanReference (org.springframework.beans.factory.config.RuntimeBeanReference)15 NoSuchBeanDefinitionException (org.springframework.beans.factory.NoSuchBeanDefinitionException)14 UnsatisfiedDependencyException (org.springframework.beans.factory.UnsatisfiedDependencyException)9 BeanDefinition (org.springframework.beans.factory.config.BeanDefinition)9 ValueHolder (org.springframework.beans.factory.config.ConstructorArgumentValues.ValueHolder)8 DependencyDescriptor (org.springframework.beans.factory.config.DependencyDescriptor)8 Element (org.w3c.dom.Element)8 GenericBeanDefinition (org.springframework.beans.factory.support.GenericBeanDefinition)7 MutablePropertyValues (org.springframework.beans.MutablePropertyValues)6 BeanWrapperImpl (org.springframework.beans.BeanWrapperImpl)5 LinkedHashSet (java.util.LinkedHashSet)4 InjectionPoint (org.springframework.beans.factory.InjectionPoint)4 AbstractBeanDefinition (org.springframework.beans.factory.support.AbstractBeanDefinition)4 ManagedList (org.springframework.beans.factory.support.ManagedList)4 MethodParameter (org.springframework.core.MethodParameter)4