Search in sources :

Example 1 with BeanNameGenerator

use of org.springframework.beans.factory.support.BeanNameGenerator in project spring-framework by spring-projects.

the class ComponentScanAnnotationParser method parse.

public Set<BeanDefinitionHolder> parse(AnnotationAttributes componentScan, final String declaringClass) {
    Assert.state(this.environment != null, "Environment must not be null");
    Assert.state(this.resourceLoader != null, "ResourceLoader must not be null");
    ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(this.registry, componentScan.getBoolean("useDefaultFilters"), this.environment, this.resourceLoader);
    Class<? extends BeanNameGenerator> generatorClass = componentScan.getClass("nameGenerator");
    boolean useInheritedGenerator = (BeanNameGenerator.class == generatorClass);
    scanner.setBeanNameGenerator(useInheritedGenerator ? this.beanNameGenerator : BeanUtils.instantiateClass(generatorClass));
    ScopedProxyMode scopedProxyMode = componentScan.getEnum("scopedProxy");
    if (scopedProxyMode != ScopedProxyMode.DEFAULT) {
        scanner.setScopedProxyMode(scopedProxyMode);
    } else {
        Class<? extends ScopeMetadataResolver> resolverClass = componentScan.getClass("scopeResolver");
        scanner.setScopeMetadataResolver(BeanUtils.instantiateClass(resolverClass));
    }
    scanner.setResourcePattern(componentScan.getString("resourcePattern"));
    for (AnnotationAttributes filter : componentScan.getAnnotationArray("includeFilters")) {
        for (TypeFilter typeFilter : typeFiltersFor(filter)) {
            scanner.addIncludeFilter(typeFilter);
        }
    }
    for (AnnotationAttributes filter : componentScan.getAnnotationArray("excludeFilters")) {
        for (TypeFilter typeFilter : typeFiltersFor(filter)) {
            scanner.addExcludeFilter(typeFilter);
        }
    }
    boolean lazyInit = componentScan.getBoolean("lazyInit");
    if (lazyInit) {
        scanner.getBeanDefinitionDefaults().setLazyInit(true);
    }
    Set<String> basePackages = new LinkedHashSet<>();
    String[] basePackagesArray = componentScan.getStringArray("basePackages");
    for (String pkg : basePackagesArray) {
        String[] tokenized = StringUtils.tokenizeToStringArray(this.environment.resolvePlaceholders(pkg), ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);
        basePackages.addAll(Arrays.asList(tokenized));
    }
    for (Class<?> clazz : componentScan.getClassArray("basePackageClasses")) {
        basePackages.add(ClassUtils.getPackageName(clazz));
    }
    if (basePackages.isEmpty()) {
        basePackages.add(ClassUtils.getPackageName(declaringClass));
    }
    scanner.addExcludeFilter(new AbstractTypeHierarchyTraversingFilter(false, false) {

        @Override
        protected boolean matchClassName(String className) {
            return declaringClass.equals(className);
        }
    });
    return scanner.doScan(StringUtils.toStringArray(basePackages));
}
Also used : LinkedHashSet(java.util.LinkedHashSet) AnnotationAttributes(org.springframework.core.annotation.AnnotationAttributes) AbstractTypeHierarchyTraversingFilter(org.springframework.core.type.filter.AbstractTypeHierarchyTraversingFilter) TypeFilter(org.springframework.core.type.filter.TypeFilter) RegexPatternTypeFilter(org.springframework.core.type.filter.RegexPatternTypeFilter) AspectJTypeFilter(org.springframework.core.type.filter.AspectJTypeFilter) AssignableTypeFilter(org.springframework.core.type.filter.AssignableTypeFilter) AnnotationTypeFilter(org.springframework.core.type.filter.AnnotationTypeFilter) BeanNameGenerator(org.springframework.beans.factory.support.BeanNameGenerator)

Example 2 with BeanNameGenerator

use of org.springframework.beans.factory.support.BeanNameGenerator in project spring-boot by spring-projects.

the class SpringApplicationTests method customBeanNameGeneratorWithNonWebApplication.

@Test
public void customBeanNameGeneratorWithNonWebApplication() throws Exception {
    TestSpringApplication application = new TestSpringApplication(ExampleWebConfig.class);
    application.setWebApplicationType(WebApplicationType.NONE);
    BeanNameGenerator beanNameGenerator = new DefaultBeanNameGenerator();
    application.setBeanNameGenerator(beanNameGenerator);
    this.context = application.run();
    verify(application.getLoader()).setBeanNameGenerator(beanNameGenerator);
    Object actualGenerator = this.context.getBean(AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR);
    assertThat(actualGenerator).isSameAs(beanNameGenerator);
}
Also used : DefaultBeanNameGenerator(org.springframework.beans.factory.support.DefaultBeanNameGenerator) BeanNameGenerator(org.springframework.beans.factory.support.BeanNameGenerator) DefaultBeanNameGenerator(org.springframework.beans.factory.support.DefaultBeanNameGenerator) Test(org.junit.Test)

Example 3 with BeanNameGenerator

use of org.springframework.beans.factory.support.BeanNameGenerator in project spring-boot by spring-projects.

the class SpringApplicationTests method customBeanNameGenerator.

@Test
public void customBeanNameGenerator() throws Exception {
    TestSpringApplication application = new TestSpringApplication(ExampleWebConfig.class);
    BeanNameGenerator beanNameGenerator = new DefaultBeanNameGenerator();
    application.setBeanNameGenerator(beanNameGenerator);
    this.context = application.run();
    verify(application.getLoader()).setBeanNameGenerator(beanNameGenerator);
    Object actualGenerator = this.context.getBean(AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR);
    assertThat(actualGenerator).isSameAs(beanNameGenerator);
}
Also used : DefaultBeanNameGenerator(org.springframework.beans.factory.support.DefaultBeanNameGenerator) BeanNameGenerator(org.springframework.beans.factory.support.BeanNameGenerator) DefaultBeanNameGenerator(org.springframework.beans.factory.support.DefaultBeanNameGenerator) Test(org.junit.Test)

Example 4 with BeanNameGenerator

use of org.springframework.beans.factory.support.BeanNameGenerator in project spring-framework by spring-projects.

the class AnnotationConfigWebApplicationContext method loadBeanDefinitions.

/**
	 * Register a {@link org.springframework.beans.factory.config.BeanDefinition} for
	 * any classes specified by {@link #register(Class...)} and scan any packages
	 * specified by {@link #scan(String...)}.
	 * <p>For any values specified by {@link #setConfigLocation(String)} or
	 * {@link #setConfigLocations(String[])}, attempt first to load each location as a
	 * class, registering a {@code BeanDefinition} if class loading is successful,
	 * and if class loading fails (i.e. a {@code ClassNotFoundException} is raised),
	 * assume the value is a package and attempt to scan it for annotated classes.
	 * <p>Enables the default set of annotation configuration post processors, such that
	 * {@code @Autowired}, {@code @Required}, and associated annotations can be used.
	 * <p>Configuration class bean definitions are registered with generated bean
	 * definition names unless the {@code value} attribute is provided to the stereotype
	 * annotation.
	 * @param beanFactory the bean factory to load bean definitions into
	 * @see #register(Class...)
	 * @see #scan(String...)
	 * @see #setConfigLocation(String)
	 * @see #setConfigLocations(String[])
	 * @see AnnotatedBeanDefinitionReader
	 * @see ClassPathBeanDefinitionScanner
	 */
@Override
protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) {
    AnnotatedBeanDefinitionReader reader = getAnnotatedBeanDefinitionReader(beanFactory);
    ClassPathBeanDefinitionScanner scanner = getClassPathBeanDefinitionScanner(beanFactory);
    BeanNameGenerator beanNameGenerator = getBeanNameGenerator();
    if (beanNameGenerator != null) {
        reader.setBeanNameGenerator(beanNameGenerator);
        scanner.setBeanNameGenerator(beanNameGenerator);
        beanFactory.registerSingleton(AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR, beanNameGenerator);
    }
    ScopeMetadataResolver scopeMetadataResolver = getScopeMetadataResolver();
    if (scopeMetadataResolver != null) {
        reader.setScopeMetadataResolver(scopeMetadataResolver);
        scanner.setScopeMetadataResolver(scopeMetadataResolver);
    }
    if (!this.annotatedClasses.isEmpty()) {
        if (logger.isInfoEnabled()) {
            logger.info("Registering annotated classes: [" + StringUtils.collectionToCommaDelimitedString(this.annotatedClasses) + "]");
        }
        reader.register(this.annotatedClasses.toArray(new Class<?>[this.annotatedClasses.size()]));
    }
    if (!this.basePackages.isEmpty()) {
        if (logger.isInfoEnabled()) {
            logger.info("Scanning base packages: [" + StringUtils.collectionToCommaDelimitedString(this.basePackages) + "]");
        }
        scanner.scan(this.basePackages.toArray(new String[this.basePackages.size()]));
    }
    String[] configLocations = getConfigLocations();
    if (configLocations != null) {
        for (String configLocation : configLocations) {
            try {
                Class<?> clazz = getClassLoader().loadClass(configLocation);
                if (logger.isInfoEnabled()) {
                    logger.info("Successfully resolved class for [" + configLocation + "]");
                }
                reader.register(clazz);
            } catch (ClassNotFoundException ex) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Could not load class for config location [" + configLocation + "] - trying package scan. " + ex);
                }
                int count = scanner.scan(configLocation);
                if (logger.isInfoEnabled()) {
                    if (count == 0) {
                        logger.info("No annotated classes found for specified class/package [" + configLocation + "]");
                    } else {
                        logger.info("Found " + count + " annotated classes in package [" + configLocation + "]");
                    }
                }
            }
        }
    }
}
Also used : ClassPathBeanDefinitionScanner(org.springframework.context.annotation.ClassPathBeanDefinitionScanner) BeanNameGenerator(org.springframework.beans.factory.support.BeanNameGenerator) ScopeMetadataResolver(org.springframework.context.annotation.ScopeMetadataResolver) AnnotatedBeanDefinitionReader(org.springframework.context.annotation.AnnotatedBeanDefinitionReader)

Example 5 with BeanNameGenerator

use of org.springframework.beans.factory.support.BeanNameGenerator in project spring-framework by spring-projects.

the class ConfigurationClassPostProcessor method processConfigBeanDefinitions.

/**
	 * Build and validate a configuration model based on the registry of
	 * {@link Configuration} classes.
	 */
public void processConfigBeanDefinitions(BeanDefinitionRegistry registry) {
    List<BeanDefinitionHolder> configCandidates = new ArrayList<>();
    String[] candidateNames = registry.getBeanDefinitionNames();
    for (String beanName : candidateNames) {
        BeanDefinition beanDef = registry.getBeanDefinition(beanName);
        if (ConfigurationClassUtils.isFullConfigurationClass(beanDef) || ConfigurationClassUtils.isLiteConfigurationClass(beanDef)) {
            if (logger.isDebugEnabled()) {
                logger.debug("Bean definition has already been processed as a configuration class: " + beanDef);
            }
        } else if (ConfigurationClassUtils.checkConfigurationClassCandidate(beanDef, this.metadataReaderFactory)) {
            configCandidates.add(new BeanDefinitionHolder(beanDef, beanName));
        }
    }
    // Return immediately if no @Configuration classes were found
    if (configCandidates.isEmpty()) {
        return;
    }
    // Sort by previously determined @Order value, if applicable
    Collections.sort(configCandidates, new Comparator<BeanDefinitionHolder>() {

        @Override
        public int compare(BeanDefinitionHolder bd1, BeanDefinitionHolder bd2) {
            int i1 = ConfigurationClassUtils.getOrder(bd1.getBeanDefinition());
            int i2 = ConfigurationClassUtils.getOrder(bd2.getBeanDefinition());
            return (i1 < i2) ? -1 : (i1 > i2) ? 1 : 0;
        }
    });
    // Detect any custom bean name generation strategy supplied through the enclosing application context
    SingletonBeanRegistry singletonRegistry = null;
    if (registry instanceof SingletonBeanRegistry) {
        singletonRegistry = (SingletonBeanRegistry) registry;
        if (!this.localBeanNameGeneratorSet && singletonRegistry.containsSingleton(CONFIGURATION_BEAN_NAME_GENERATOR)) {
            BeanNameGenerator generator = (BeanNameGenerator) singletonRegistry.getSingleton(CONFIGURATION_BEAN_NAME_GENERATOR);
            this.componentScanBeanNameGenerator = generator;
            this.importBeanNameGenerator = generator;
        }
    }
    // Parse each @Configuration class
    ConfigurationClassParser parser = new ConfigurationClassParser(this.metadataReaderFactory, this.problemReporter, this.environment, this.resourceLoader, this.componentScanBeanNameGenerator, registry);
    Set<BeanDefinitionHolder> candidates = new LinkedHashSet<>(configCandidates);
    Set<ConfigurationClass> alreadyParsed = new HashSet<>(configCandidates.size());
    do {
        parser.parse(candidates);
        parser.validate();
        Set<ConfigurationClass> configClasses = new LinkedHashSet<>(parser.getConfigurationClasses());
        configClasses.removeAll(alreadyParsed);
        // Read the model and create bean definitions based on its content
        if (this.reader == null) {
            this.reader = new ConfigurationClassBeanDefinitionReader(registry, this.sourceExtractor, this.resourceLoader, this.environment, this.importBeanNameGenerator, parser.getImportRegistry());
        }
        this.reader.loadBeanDefinitions(configClasses);
        alreadyParsed.addAll(configClasses);
        candidates.clear();
        if (registry.getBeanDefinitionCount() > candidateNames.length) {
            String[] newCandidateNames = registry.getBeanDefinitionNames();
            Set<String> oldCandidateNames = new HashSet<>(Arrays.asList(candidateNames));
            Set<String> alreadyParsedClasses = new HashSet<>();
            for (ConfigurationClass configurationClass : alreadyParsed) {
                alreadyParsedClasses.add(configurationClass.getMetadata().getClassName());
            }
            for (String candidateName : newCandidateNames) {
                if (!oldCandidateNames.contains(candidateName)) {
                    BeanDefinition beanDef = registry.getBeanDefinition(candidateName);
                    if (ConfigurationClassUtils.checkConfigurationClassCandidate(beanDef, this.metadataReaderFactory) && !alreadyParsedClasses.contains(beanDef.getBeanClassName())) {
                        candidates.add(new BeanDefinitionHolder(beanDef, candidateName));
                    }
                }
            }
            candidateNames = newCandidateNames;
        }
    } while (!candidates.isEmpty());
    // Register the ImportRegistry as a bean in order to support ImportAware @Configuration classes
    if (singletonRegistry != null) {
        if (!singletonRegistry.containsSingleton(IMPORT_REGISTRY_BEAN_NAME)) {
            singletonRegistry.registerSingleton(IMPORT_REGISTRY_BEAN_NAME, parser.getImportRegistry());
        }
    }
    if (this.metadataReaderFactory instanceof CachingMetadataReaderFactory) {
        // Clear cache in externally provided MetadataReaderFactory; this is a no-op
        // for a shared cache since it'll be cleared by the ApplicationContext.
        ((CachingMetadataReaderFactory) this.metadataReaderFactory).clearCache();
    }
}
Also used : LinkedHashSet(java.util.LinkedHashSet) ArrayList(java.util.ArrayList) CachingMetadataReaderFactory(org.springframework.core.type.classreading.CachingMetadataReaderFactory) SingletonBeanRegistry(org.springframework.beans.factory.config.SingletonBeanRegistry) AbstractBeanDefinition(org.springframework.beans.factory.support.AbstractBeanDefinition) BeanDefinition(org.springframework.beans.factory.config.BeanDefinition) BeanNameGenerator(org.springframework.beans.factory.support.BeanNameGenerator) BeanDefinitionHolder(org.springframework.beans.factory.config.BeanDefinitionHolder) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet)

Aggregations

BeanNameGenerator (org.springframework.beans.factory.support.BeanNameGenerator)6 LinkedHashSet (java.util.LinkedHashSet)2 Test (org.junit.Test)2 DefaultBeanNameGenerator (org.springframework.beans.factory.support.DefaultBeanNameGenerator)2 ArrayList (java.util.ArrayList)1 HashSet (java.util.HashSet)1 BeanDefinition (org.springframework.beans.factory.config.BeanDefinition)1 BeanDefinitionHolder (org.springframework.beans.factory.config.BeanDefinitionHolder)1 SingletonBeanRegistry (org.springframework.beans.factory.config.SingletonBeanRegistry)1 AbstractBeanDefinition (org.springframework.beans.factory.support.AbstractBeanDefinition)1 AnnotatedBeanDefinitionReader (org.springframework.context.annotation.AnnotatedBeanDefinitionReader)1 ClassPathBeanDefinitionScanner (org.springframework.context.annotation.ClassPathBeanDefinitionScanner)1 ScopeMetadataResolver (org.springframework.context.annotation.ScopeMetadataResolver)1 AnnotationAttributes (org.springframework.core.annotation.AnnotationAttributes)1 CachingMetadataReaderFactory (org.springframework.core.type.classreading.CachingMetadataReaderFactory)1 AbstractTypeHierarchyTraversingFilter (org.springframework.core.type.filter.AbstractTypeHierarchyTraversingFilter)1 AnnotationTypeFilter (org.springframework.core.type.filter.AnnotationTypeFilter)1 AspectJTypeFilter (org.springframework.core.type.filter.AspectJTypeFilter)1 AssignableTypeFilter (org.springframework.core.type.filter.AssignableTypeFilter)1 RegexPatternTypeFilter (org.springframework.core.type.filter.RegexPatternTypeFilter)1