Search in sources :

Example 1 with MethodMetadata

use of org.springframework.core.type.MethodMetadata in project spring-framework by spring-projects.

the class ConfigurationClassBeanDefinitionReader method loadBeanDefinitionsForBeanMethod.

/**
	 * Read the given {@link BeanMethod}, registering bean definitions
	 * with the BeanDefinitionRegistry based on its contents.
	 */
private void loadBeanDefinitionsForBeanMethod(BeanMethod beanMethod) {
    ConfigurationClass configClass = beanMethod.getConfigurationClass();
    MethodMetadata metadata = beanMethod.getMetadata();
    String methodName = metadata.getMethodName();
    // Do we need to mark the bean as skipped by its condition?
    if (this.conditionEvaluator.shouldSkip(metadata, ConfigurationPhase.REGISTER_BEAN)) {
        configClass.skippedBeanMethods.add(methodName);
        return;
    }
    if (configClass.skippedBeanMethods.contains(methodName)) {
        return;
    }
    // Consider name and any aliases
    AnnotationAttributes bean = AnnotationConfigUtils.attributesFor(metadata, Bean.class);
    List<String> names = new ArrayList<>(Arrays.asList(bean.getStringArray("name")));
    String beanName = (names.size() > 0 ? names.remove(0) : methodName);
    // Register aliases even when overridden
    for (String alias : names) {
        this.registry.registerAlias(beanName, alias);
    }
    // Has this effectively been overridden before (e.g. via XML)?
    if (isOverriddenByExistingDefinition(beanMethod, beanName)) {
        return;
    }
    ConfigurationClassBeanDefinition beanDef = new ConfigurationClassBeanDefinition(configClass, metadata);
    beanDef.setResource(configClass.getResource());
    beanDef.setSource(this.sourceExtractor.extractSource(metadata, configClass.getResource()));
    if (metadata.isStatic()) {
        // static @Bean method
        beanDef.setBeanClassName(configClass.getMetadata().getClassName());
        beanDef.setFactoryMethodName(methodName);
    } else {
        // instance @Bean method
        beanDef.setFactoryBeanName(configClass.getBeanName());
        beanDef.setUniqueFactoryMethodName(methodName);
    }
    beanDef.setAutowireMode(RootBeanDefinition.AUTOWIRE_CONSTRUCTOR);
    beanDef.setAttribute(RequiredAnnotationBeanPostProcessor.SKIP_REQUIRED_CHECK_ATTRIBUTE, Boolean.TRUE);
    AnnotationConfigUtils.processCommonDefinitionAnnotations(beanDef, metadata);
    Autowire autowire = bean.getEnum("autowire");
    if (autowire.isAutowire()) {
        beanDef.setAutowireMode(autowire.value());
    }
    String initMethodName = bean.getString("initMethod");
    if (StringUtils.hasText(initMethodName)) {
        beanDef.setInitMethodName(initMethodName);
    }
    String destroyMethodName = bean.getString("destroyMethod");
    if (destroyMethodName != null) {
        beanDef.setDestroyMethodName(destroyMethodName);
    }
    // Consider scoping
    ScopedProxyMode proxyMode = ScopedProxyMode.NO;
    AnnotationAttributes attributes = AnnotationConfigUtils.attributesFor(metadata, Scope.class);
    if (attributes != null) {
        beanDef.setScope(attributes.getString("value"));
        proxyMode = attributes.getEnum("proxyMode");
        if (proxyMode == ScopedProxyMode.DEFAULT) {
            proxyMode = ScopedProxyMode.NO;
        }
    }
    // Replace the original bean definition with the target one, if necessary
    BeanDefinition beanDefToRegister = beanDef;
    if (proxyMode != ScopedProxyMode.NO) {
        BeanDefinitionHolder proxyDef = ScopedProxyCreator.createScopedProxy(new BeanDefinitionHolder(beanDef, beanName), this.registry, proxyMode == ScopedProxyMode.TARGET_CLASS);
        beanDefToRegister = new ConfigurationClassBeanDefinition((RootBeanDefinition) proxyDef.getBeanDefinition(), configClass, metadata);
    }
    if (logger.isDebugEnabled()) {
        logger.debug(String.format("Registering bean definition for @Bean method %s.%s()", configClass.getMetadata().getClassName(), beanName));
    }
    this.registry.registerBeanDefinition(beanName, beanDefToRegister);
}
Also used : AnnotationAttributes(org.springframework.core.annotation.AnnotationAttributes) BeanDefinitionHolder(org.springframework.beans.factory.config.BeanDefinitionHolder) ArrayList(java.util.ArrayList) RootBeanDefinition(org.springframework.beans.factory.support.RootBeanDefinition) MethodMetadata(org.springframework.core.type.MethodMetadata) RootBeanDefinition(org.springframework.beans.factory.support.RootBeanDefinition) AnnotatedBeanDefinition(org.springframework.beans.factory.annotation.AnnotatedBeanDefinition) BeanDefinition(org.springframework.beans.factory.config.BeanDefinition) AnnotatedGenericBeanDefinition(org.springframework.beans.factory.annotation.AnnotatedGenericBeanDefinition) Autowire(org.springframework.beans.factory.annotation.Autowire)

Example 2 with MethodMetadata

use of org.springframework.core.type.MethodMetadata in project spring-cloud-config by spring-cloud.

the class CompositeUtils method getEnvironmentRepositoryFactoryTypeParams.

/**
 * Given a Factory Name return the generic type parameters of the factory (The actual repository class, and its properties class)o
 */
public static Type[] getEnvironmentRepositoryFactoryTypeParams(ConfigurableListableBeanFactory beanFactory, String factoryName) {
    MethodMetadata methodMetadata = (MethodMetadata) beanFactory.getBeanDefinition(factoryName).getSource();
    Class<?> factoryClass = null;
    try {
        factoryClass = Class.forName(methodMetadata.getReturnTypeName());
    } catch (ClassNotFoundException e) {
        throw new IllegalStateException(e);
    }
    Optional<AnnotatedType> annotatedFactoryType = Arrays.stream(factoryClass.getAnnotatedInterfaces()).filter(i -> {
        ParameterizedType parameterizedType = (ParameterizedType) i.getType();
        return parameterizedType.getRawType().equals(EnvironmentRepositoryFactory.class);
    }).findFirst();
    ParameterizedType factoryParameterizedType = (ParameterizedType) annotatedFactoryType.orElse(factoryClass.getAnnotatedSuperclass()).getType();
    return factoryParameterizedType.getActualTypeArguments();
}
Also used : Arrays(java.util.Arrays) MethodMetadata(org.springframework.core.type.MethodMetadata) AnnotatedType(java.lang.reflect.AnnotatedType) BeanFactoryUtils(org.springframework.beans.factory.BeanFactoryUtils) Collectors(java.util.stream.Collectors) ConfigurableListableBeanFactory(org.springframework.beans.factory.config.ConfigurableListableBeanFactory) List(java.util.List) ParameterizedType(java.lang.reflect.ParameterizedType) EnvironmentRepositoryFactory(org.springframework.cloud.config.server.environment.EnvironmentRepositoryFactory) Type(java.lang.reflect.Type) Environment(org.springframework.core.env.Environment) Map(java.util.Map) Optional(java.util.Optional) Binder(org.springframework.boot.context.properties.bind.Binder) ParameterizedType(java.lang.reflect.ParameterizedType) AnnotatedType(java.lang.reflect.AnnotatedType) MethodMetadata(org.springframework.core.type.MethodMetadata) EnvironmentRepositoryFactory(org.springframework.cloud.config.server.environment.EnvironmentRepositoryFactory)

Example 3 with MethodMetadata

use of org.springframework.core.type.MethodMetadata in project spring-integration by spring-projects.

the class IntegrationConverterInitializer method initialize.

@Override
public void initialize(ConfigurableListableBeanFactory beanFactory) throws BeansException {
    BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
    for (String beanName : registry.getBeanDefinitionNames()) {
        BeanDefinition beanDefinition = registry.getBeanDefinition(beanName);
        if (beanDefinition instanceof AnnotatedBeanDefinition) {
            AnnotationMetadata metadata = ((AnnotatedBeanDefinition) beanDefinition).getMetadata();
            boolean hasIntegrationConverter = metadata.hasAnnotation(IntegrationConverter.class.getName());
            if (!hasIntegrationConverter && beanDefinition.getSource() instanceof MethodMetadata) {
                MethodMetadata beanMethod = (MethodMetadata) beanDefinition.getSource();
                hasIntegrationConverter = beanMethod.isAnnotated(IntegrationConverter.class.getName());
            }
            if (hasIntegrationConverter) {
                this.registerConverter(registry, new RuntimeBeanReference(beanName));
            }
        }
    }
}
Also used : AnnotatedBeanDefinition(org.springframework.beans.factory.annotation.AnnotatedBeanDefinition) BeanDefinitionRegistry(org.springframework.beans.factory.support.BeanDefinitionRegistry) MethodMetadata(org.springframework.core.type.MethodMetadata) RootBeanDefinition(org.springframework.beans.factory.support.RootBeanDefinition) AnnotatedBeanDefinition(org.springframework.beans.factory.annotation.AnnotatedBeanDefinition) BeanDefinition(org.springframework.beans.factory.config.BeanDefinition) RuntimeBeanReference(org.springframework.beans.factory.config.RuntimeBeanReference) AnnotationMetadata(org.springframework.core.type.AnnotationMetadata)

Example 4 with MethodMetadata

use of org.springframework.core.type.MethodMetadata in project BroadleafCommerce by BroadleafCommerce.

the class MergeAnnotationAwareBeanDefinitionRegistryPostProcessor method postProcessBeanDefinitionRegistry.

@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
    Map<String, BeanDefinition> clientAnnotatedBeanPostProcessors = new LinkedHashMap<>();
    Map<String, BeanDefinition> clientBeanPostProcessors = new LinkedHashMap<>();
    for (String name : registry.getBeanDefinitionNames()) {
        BeanDefinition beanDefinition = registry.getBeanDefinition(name);
        if (beanDefinition instanceof AnnotatedBeanDefinition) {
            MethodMetadata metadata = ((AnnotatedBeanDefinition) beanDefinition).getFactoryMethodMetadata();
            if (metadata != null) {
                Map<String, Object> attributes = metadata.getAnnotationAttributes(Merge.class.getName());
                if (!MapUtils.isEmpty(attributes)) {
                    boolean isEarly = MapUtils.getBooleanValue(attributes, "early");
                    BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(isEarly ? EarlyStageMergeBeanPostProcessor.class : LateStageMergeBeanPostProcessor.class).setScope(BeanDefinition.SCOPE_SINGLETON).addPropertyValue("sourceRef", name).addPropertyValue("targetRef", attributes.get("targetRef")).addPropertyValue("placement", attributes.get("placement")).addPropertyValue("position", attributes.get("position"));
                    Class<MergeBeanStatusProvider> clazz = (Class<MergeBeanStatusProvider>) attributes.get("statusProvider");
                    if (MergeBeanStatusProvider.class != clazz) {
                        try {
                            builder.addPropertyValue("statusProvider", clazz.newInstance());
                        } catch (InstantiationException e) {
                            throw ExceptionHelper.refineException(e);
                        } catch (IllegalAccessException e) {
                            throw ExceptionHelper.refineException(e);
                        }
                    }
                    BeanDefinition definition = builder.getBeanDefinition();
                    String beanName = name + "_" + attributes.get("targetRef") + (isEarly ? "Early" : "Late") + ANNOTATED_POST_PROCESSOR_SUFFIX;
                    if (isBroadleafAnnotationBean(metadata)) {
                        registry.registerBeanDefinition(beanName, definition);
                    } else {
                        clientAnnotatedBeanPostProcessors.put(beanName, definition);
                    }
                }
            }
        }
        /*
                If this is a client bean post processor, then remove it and store it away until we register all
                framework post processors.
             */
        if (beanDefinition.getBeanClassName() != null && (beanDefinition.getBeanClassName().equals(EarlyStageMergeBeanPostProcessor.class.getName()) || beanDefinition.getBeanClassName().equals(LateStageMergeBeanPostProcessor.class.getName()))) {
            if (!isBroadleafBean(beanDefinition)) {
                registry.removeBeanDefinition(name);
                clientBeanPostProcessors.put(name, beanDefinition);
            }
        }
    }
    if (org.apache.commons.collections4.MapUtils.isNotEmpty(clientBeanPostProcessors)) {
        for (Map.Entry<String, BeanDefinition> entry : clientBeanPostProcessors.entrySet()) {
            registry.registerBeanDefinition(entry.getKey(), entry.getValue());
        }
    }
    if (org.apache.commons.collections4.MapUtils.isNotEmpty(clientAnnotatedBeanPostProcessors)) {
        for (Map.Entry<String, BeanDefinition> entry : clientAnnotatedBeanPostProcessors.entrySet()) {
            registry.registerBeanDefinition(entry.getKey(), entry.getValue());
        }
    }
}
Also used : AnnotatedBeanDefinition(org.springframework.beans.factory.annotation.AnnotatedBeanDefinition) AnnotatedBeanDefinition(org.springframework.beans.factory.annotation.AnnotatedBeanDefinition) GenericBeanDefinition(org.springframework.beans.factory.support.GenericBeanDefinition) BeanDefinition(org.springframework.beans.factory.config.BeanDefinition) LinkedHashMap(java.util.LinkedHashMap) BeanDefinitionBuilder(org.springframework.beans.factory.support.BeanDefinitionBuilder) MethodMetadata(org.springframework.core.type.MethodMetadata) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map)

Example 5 with MethodMetadata

use of org.springframework.core.type.MethodMetadata in project spring-boot by spring-projects.

the class OnAvailableEndpointCondition method getTarget.

private Class<?> getTarget(ConditionContext context, AnnotatedTypeMetadata metadata, MergedAnnotation<ConditionalOnAvailableEndpoint> condition) {
    Class<?> target = condition.getClass("endpoint");
    if (target != Void.class) {
        return target;
    }
    Assert.state(metadata instanceof MethodMetadata && metadata.isAnnotated(Bean.class.getName()), "EndpointCondition must be used on @Bean methods when the endpoint is not specified");
    MethodMetadata methodMetadata = (MethodMetadata) metadata;
    try {
        return ClassUtils.forName(methodMetadata.getReturnTypeName(), context.getClassLoader());
    } catch (Throwable ex) {
        throw new IllegalStateException("Failed to extract endpoint id for " + methodMetadata.getDeclaringClassName() + "." + methodMetadata.getMethodName(), ex);
    }
}
Also used : MethodMetadata(org.springframework.core.type.MethodMetadata) Bean(org.springframework.context.annotation.Bean)

Aggregations

MethodMetadata (org.springframework.core.type.MethodMetadata)18 AnnotatedBeanDefinition (org.springframework.beans.factory.annotation.AnnotatedBeanDefinition)7 BeanDefinition (org.springframework.beans.factory.config.BeanDefinition)7 Map (java.util.Map)5 BeanDefinitionRegistry (org.springframework.beans.factory.support.BeanDefinitionRegistry)4 AnnotationMetadata (org.springframework.core.type.AnnotationMetadata)4 Test (org.junit.Test)3 BeanDefinitionBuilder (org.springframework.beans.factory.support.BeanDefinitionBuilder)3 RootBeanDefinition (org.springframework.beans.factory.support.RootBeanDefinition)3 LinkedHashMap (java.util.LinkedHashMap)2 BeanDefinitionHolder (org.springframework.beans.factory.config.BeanDefinitionHolder)2 ManagedMap (org.springframework.beans.factory.support.ManagedMap)2 Bean (org.springframework.context.annotation.Bean)2 AnnotationAttributes (org.springframework.core.annotation.AnnotationAttributes)2 StandardMethodMetadata (org.springframework.core.type.StandardMethodMetadata)2 MethodsMetadata (org.springframework.data.type.MethodsMetadata)2 IOException (java.io.IOException)1 AnnotatedType (java.lang.reflect.AnnotatedType)1 ParameterizedType (java.lang.reflect.ParameterizedType)1 Type (java.lang.reflect.Type)1