Search in sources :

Example 81 with BeanDefinitionHolder

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

the class InjectAnnotationAutowireContextTests method testAutowiredMethodParameterWithStaticallyQualifiedCandidate.

@Test
public void testAutowiredMethodParameterWithStaticallyQualifiedCandidate() {
    GenericApplicationContext context = new GenericApplicationContext();
    ConstructorArgumentValues cavs = new ConstructorArgumentValues();
    cavs.addGenericArgumentValue(JUERGEN);
    RootBeanDefinition person = new RootBeanDefinition(QualifiedPerson.class, cavs, null);
    context.registerBeanDefinition(JUERGEN, ScopedProxyUtils.createScopedProxy(new BeanDefinitionHolder(person, JUERGEN), context, true).getBeanDefinition());
    context.registerBeanDefinition("autowired", new RootBeanDefinition(QualifiedMethodParameterTestBean.class));
    AnnotationConfigUtils.registerAnnotationConfigProcessors(context);
    context.refresh();
    QualifiedMethodParameterTestBean bean = (QualifiedMethodParameterTestBean) context.getBean("autowired");
    assertThat(bean.getPerson().getName()).isEqualTo(JUERGEN);
}
Also used : GenericApplicationContext(org.springframework.context.support.GenericApplicationContext) BeanDefinitionHolder(org.springframework.beans.factory.config.BeanDefinitionHolder) ConstructorArgumentValues(org.springframework.beans.factory.config.ConstructorArgumentValues) Test(org.junit.jupiter.api.Test)

Example 82 with BeanDefinitionHolder

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

the class AnnotationConfigUtils method registerAnnotationConfigProcessors.

/**
 * Register all relevant annotation post processors in the given registry.
 * @param registry the registry to operate on
 * @param source the configuration source element (already extracted)
 * that this registration was triggered from. May be {@code null}.
 * @return a Set of BeanDefinitionHolders, containing all bean definitions
 * that have actually been registered by this call
 */
public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors(BeanDefinitionRegistry registry, @Nullable Object source) {
    DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry);
    if (beanFactory != null) {
        if (!(beanFactory.getDependencyComparator() instanceof AnnotationAwareOrderComparator)) {
            beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE);
        }
        if (!(beanFactory.getAutowireCandidateResolver() instanceof ContextAnnotationAutowireCandidateResolver)) {
            beanFactory.setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver());
        }
    }
    Set<BeanDefinitionHolder> beanDefs = new LinkedHashSet<>(8);
    if (!registry.containsBeanDefinition(CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)) {
        RootBeanDefinition def = new RootBeanDefinition(ConfigurationClassPostProcessor.class);
        def.setSource(source);
        beanDefs.add(registerPostProcessor(registry, def, CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME));
    }
    if (!registry.containsBeanDefinition(AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) {
        RootBeanDefinition def = new RootBeanDefinition(AutowiredAnnotationBeanPostProcessor.class);
        def.setSource(source);
        beanDefs.add(registerPostProcessor(registry, def, AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
    }
    // Check for Jakarta Annotations support, and if present add the CommonAnnotationBeanPostProcessor.
    if (jakartaAnnotationsPresent && !registry.containsBeanDefinition(COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)) {
        RootBeanDefinition def = new RootBeanDefinition(CommonAnnotationBeanPostProcessor.class);
        def.setSource(source);
        beanDefs.add(registerPostProcessor(registry, def, COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));
    }
    // for the javax variant of PostConstruct/PreDestroy.
    if (jsr250Present && !registry.containsBeanDefinition(JSR250_ANNOTATION_PROCESSOR_BEAN_NAME)) {
        try {
            RootBeanDefinition def = new RootBeanDefinition(InitDestroyAnnotationBeanPostProcessor.class);
            def.getPropertyValues().add("initAnnotationType", classLoader.loadClass("javax.annotation.PostConstruct"));
            def.getPropertyValues().add("destroyAnnotationType", classLoader.loadClass("javax.annotation.PreDestroy"));
            def.setSource(source);
            beanDefs.add(registerPostProcessor(registry, def, JSR250_ANNOTATION_PROCESSOR_BEAN_NAME));
        } catch (ClassNotFoundException ex) {
        // Failed to load javax variants of the annotation types -> ignore.
        }
    }
    // Check for JPA support, and if present add the PersistenceAnnotationBeanPostProcessor.
    if (jpaPresent && !registry.containsBeanDefinition(PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME)) {
        RootBeanDefinition def = new RootBeanDefinition();
        try {
            def.setBeanClass(ClassUtils.forName(PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME, AnnotationConfigUtils.class.getClassLoader()));
        } catch (ClassNotFoundException ex) {
            throw new IllegalStateException("Cannot load optional framework class: " + PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME, ex);
        }
        def.setSource(source);
        beanDefs.add(registerPostProcessor(registry, def, PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME));
    }
    if (!registry.containsBeanDefinition(EVENT_LISTENER_PROCESSOR_BEAN_NAME)) {
        RootBeanDefinition def = new RootBeanDefinition(EventListenerMethodProcessor.class);
        def.setSource(source);
        beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_PROCESSOR_BEAN_NAME));
    }
    if (!registry.containsBeanDefinition(EVENT_LISTENER_FACTORY_BEAN_NAME)) {
        RootBeanDefinition def = new RootBeanDefinition(DefaultEventListenerFactory.class);
        def.setSource(source);
        beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_FACTORY_BEAN_NAME));
    }
    return beanDefs;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) BeanDefinitionHolder(org.springframework.beans.factory.config.BeanDefinitionHolder) DefaultListableBeanFactory(org.springframework.beans.factory.support.DefaultListableBeanFactory) RootBeanDefinition(org.springframework.beans.factory.support.RootBeanDefinition) AnnotationAwareOrderComparator(org.springframework.core.annotation.AnnotationAwareOrderComparator)

Example 83 with BeanDefinitionHolder

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

the class AnnotatedBeanDefinitionReader method doRegisterBean.

/**
 * Register a bean from the given bean class, deriving its metadata from
 * class-declared annotations.
 * @param beanClass the class of the bean
 * @param name an explicit name for the bean
 * @param qualifiers specific qualifier annotations to consider, if any,
 * in addition to qualifiers at the bean class level
 * @param supplier a callback for creating an instance of the bean
 * (may be {@code null})
 * @param customizers one or more callbacks for customizing the factory's
 * {@link BeanDefinition}, e.g. setting a lazy-init or primary flag
 * @since 5.0
 */
private <T> void doRegisterBean(Class<T> beanClass, @Nullable String name, @Nullable Class<? extends Annotation>[] qualifiers, @Nullable Supplier<T> supplier, @Nullable BeanDefinitionCustomizer[] customizers) {
    AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(beanClass);
    if (this.conditionEvaluator.shouldSkip(abd.getMetadata())) {
        return;
    }
    abd.setInstanceSupplier(supplier);
    ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(abd);
    abd.setScope(scopeMetadata.getScopeName());
    String beanName = (name != null ? name : this.beanNameGenerator.generateBeanName(abd, this.registry));
    AnnotationConfigUtils.processCommonDefinitionAnnotations(abd);
    if (qualifiers != null) {
        for (Class<? extends Annotation> qualifier : qualifiers) {
            if (Primary.class == qualifier) {
                abd.setPrimary(true);
            } else if (Lazy.class == qualifier) {
                abd.setLazyInit(true);
            } else {
                abd.addQualifier(new AutowireCandidateQualifier(qualifier));
            }
        }
    }
    if (customizers != null) {
        for (BeanDefinitionCustomizer customizer : customizers) {
            customizer.customize(abd);
        }
    }
    BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName);
    definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
    BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry);
}
Also used : BeanDefinitionHolder(org.springframework.beans.factory.config.BeanDefinitionHolder) BeanDefinitionCustomizer(org.springframework.beans.factory.config.BeanDefinitionCustomizer) AnnotatedGenericBeanDefinition(org.springframework.beans.factory.annotation.AnnotatedGenericBeanDefinition) AutowireCandidateQualifier(org.springframework.beans.factory.support.AutowireCandidateQualifier)

Example 84 with BeanDefinitionHolder

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

the class ConfigurationClassPostProcessorTests method postProcessorDoesNotOverrideRegularBeanDefinitionsEvenWithScopedProxy.

@Test
void postProcessorDoesNotOverrideRegularBeanDefinitionsEvenWithScopedProxy() {
    RootBeanDefinition rbd = new RootBeanDefinition(TestBean.class);
    rbd.setResource(new DescriptiveResource("XML or something"));
    BeanDefinitionHolder proxied = ScopedProxyUtils.createScopedProxy(new BeanDefinitionHolder(rbd, "bar"), beanFactory, true);
    beanFactory.registerBeanDefinition("bar", proxied.getBeanDefinition());
    beanFactory.registerBeanDefinition("config", new RootBeanDefinition(SingletonBeanConfig.class));
    ConfigurationClassPostProcessor pp = new ConfigurationClassPostProcessor();
    pp.postProcessBeanFactory(beanFactory);
    beanFactory.getBean("foo", Foo.class);
    beanFactory.getBean("bar", TestBean.class);
}
Also used : BeanDefinitionHolder(org.springframework.beans.factory.config.BeanDefinitionHolder) RootBeanDefinition(org.springframework.beans.factory.support.RootBeanDefinition) DescriptiveResource(org.springframework.core.io.DescriptiveResource) Test(org.junit.jupiter.api.Test)

Example 85 with BeanDefinitionHolder

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

the class AbstractInterceptorDrivenBeanDefinitionDecorator method decorate.

@Override
public final BeanDefinitionHolder decorate(Node node, BeanDefinitionHolder definitionHolder, ParserContext parserContext) {
    BeanDefinitionRegistry registry = parserContext.getRegistry();
    // get the root bean name - will be the name of the generated proxy factory bean
    String existingBeanName = definitionHolder.getBeanName();
    BeanDefinition targetDefinition = definitionHolder.getBeanDefinition();
    BeanDefinitionHolder targetHolder = new BeanDefinitionHolder(targetDefinition, existingBeanName + ".TARGET");
    // delegate to subclass for interceptor definition
    BeanDefinition interceptorDefinition = createInterceptorDefinition(node);
    // generate name and register the interceptor
    String interceptorName = existingBeanName + '.' + getInterceptorNameSuffix(interceptorDefinition);
    BeanDefinitionReaderUtils.registerBeanDefinition(new BeanDefinitionHolder(interceptorDefinition, interceptorName), registry);
    BeanDefinitionHolder result = definitionHolder;
    if (!isProxyFactoryBeanDefinition(targetDefinition)) {
        // create the proxy definition
        RootBeanDefinition proxyDefinition = new RootBeanDefinition();
        // create proxy factory bean definition
        proxyDefinition.setBeanClass(ProxyFactoryBean.class);
        proxyDefinition.setScope(targetDefinition.getScope());
        proxyDefinition.setLazyInit(targetDefinition.isLazyInit());
        // set the target
        proxyDefinition.setDecoratedDefinition(targetHolder);
        proxyDefinition.getPropertyValues().add("target", targetHolder);
        // create the interceptor names list
        proxyDefinition.getPropertyValues().add("interceptorNames", new ManagedList<String>());
        // copy autowire settings from original bean definition.
        proxyDefinition.setAutowireCandidate(targetDefinition.isAutowireCandidate());
        proxyDefinition.setPrimary(targetDefinition.isPrimary());
        if (targetDefinition instanceof AbstractBeanDefinition) {
            proxyDefinition.copyQualifiersFrom((AbstractBeanDefinition) targetDefinition);
        }
        // wrap it in a BeanDefinitionHolder with bean name
        result = new BeanDefinitionHolder(proxyDefinition, existingBeanName);
    }
    addInterceptorNameToList(interceptorName, result.getBeanDefinition());
    return result;
}
Also used : AbstractBeanDefinition(org.springframework.beans.factory.support.AbstractBeanDefinition) BeanDefinitionHolder(org.springframework.beans.factory.config.BeanDefinitionHolder) BeanDefinitionRegistry(org.springframework.beans.factory.support.BeanDefinitionRegistry) 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)

Aggregations

BeanDefinitionHolder (org.springframework.beans.factory.config.BeanDefinitionHolder)94 BeanDefinition (org.springframework.beans.factory.config.BeanDefinition)30 RootBeanDefinition (org.springframework.beans.factory.support.RootBeanDefinition)20 AbstractBeanDefinition (org.springframework.beans.factory.support.AbstractBeanDefinition)18 Element (org.w3c.dom.Element)18 BeanComponentDefinition (org.springframework.beans.factory.parsing.BeanComponentDefinition)16 BeanDefinitionBuilder (org.springframework.beans.factory.support.BeanDefinitionBuilder)16 RuntimeBeanReference (org.springframework.beans.factory.config.RuntimeBeanReference)12 ManagedList (org.springframework.beans.factory.support.ManagedList)11 Node (org.w3c.dom.Node)11 ArrayList (java.util.ArrayList)8 ManagedMap (org.springframework.beans.factory.support.ManagedMap)6 LinkedHashSet (java.util.LinkedHashSet)5 Test (org.junit.jupiter.api.Test)5 BeanDefinitionStoreException (org.springframework.beans.factory.BeanDefinitionStoreException)5 AnnotatedGenericBeanDefinition (org.springframework.beans.factory.annotation.AnnotatedGenericBeanDefinition)5 NamedNodeMap (org.w3c.dom.NamedNodeMap)5 NodeList (org.w3c.dom.NodeList)5 Method (java.lang.reflect.Method)4 HashSet (java.util.HashSet)4