org.springframework.beans.factory.support.BeanNameGenerator Java Examples

The following examples show how to use org.springframework.beans.factory.support.BeanNameGenerator. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AnnotationBeanDefinitionRegistryPostProcessor.java    From spring-context-support with Apache License 2.0 6 votes vote down vote up
private void registerBeanDefinitions(BeanDefinitionRegistry registry, String[] basePackages) {

        ExposingClassPathBeanDefinitionScanner scanner = new ExposingClassPathBeanDefinitionScanner(registry, false,
                getEnvironment(), getResourceLoader());

        BeanNameGenerator beanNameGenerator = resolveAnnotatedBeanNameGenerator(registry);
        // Set the BeanNameGenerator
        scanner.setBeanNameGenerator(beanNameGenerator);
        // Add the AnnotationTypeFilter for annotationTypes
        for (Class<? extends Annotation> supportedAnnotationType : getSupportedAnnotationTypes()) {
            scanner.addIncludeFilter(new AnnotationTypeFilter(supportedAnnotationType));
        }
        // Register the primary BeanDefinitions
        Map<String, AnnotatedBeanDefinition> primaryBeanDefinitions = registerPrimaryBeanDefinitions(scanner, basePackages);
        // Register the secondary BeanDefinitions
        registerSecondaryBeanDefinitions(scanner, primaryBeanDefinitions, basePackages);
    }
 
Example #2
Source File: SpringBeanRegister.java    From springboot-plugin-framework-parent with Apache License 2.0 6 votes vote down vote up
/**
 * 默认注册
 * @param pluginId 插件id
 * @param suffixName bean 后缀名称
 * @param aClass 注册的类
 * @param consumer 自定义处理AnnotatedGenericBeanDefinition
 * @return 注册的bean名称
 */
public String register(String pluginId, String suffixName, Class<?> aClass,
                       Consumer<AnnotatedGenericBeanDefinition> consumer) {
    AnnotatedGenericBeanDefinition beanDefinition = new
            AnnotatedGenericBeanDefinition(aClass);

    BeanNameGenerator beanNameGenerator =
            new PluginAnnotationBeanNameGenerator(suffixName);
    String beanName = beanNameGenerator.generateBeanName(beanDefinition, applicationContext);
    if(PluginInfoContainer.existRegisterBeanName((beanName))){
        String error = MessageFormat.format("Bean name {0} already exist of {1}",
                beanName, aClass.getName());
        logger.error(error);
        return null;
    }
    if(consumer != null){
        consumer.accept(beanDefinition);
    }
    applicationContext.registerBeanDefinition(beanName, beanDefinition);
    PluginInfoContainer.addRegisterBeanName(pluginId, beanName);
    return beanName;
}
 
Example #3
Source File: ClassPathBeanDefinitionScannerScopeIntegrationTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
private ApplicationContext createContext(ScopedProxyMode scopedProxyMode) {
	GenericWebApplicationContext context = new GenericWebApplicationContext();
	ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context);
	scanner.setIncludeAnnotationConfig(false);
	scanner.setBeanNameGenerator(new BeanNameGenerator() {
		@Override
		public String generateBeanName(BeanDefinition definition, BeanDefinitionRegistry registry) {
			return definition.getScope();
		}
	});
	scanner.setScopedProxyMode(scopedProxyMode);

	// Scan twice in order to find errors in the bean definition compatibility check.
	scanner.scan(getClass().getPackage().getName());
	scanner.scan(getClass().getPackage().getName());

	context.refresh();
	return context;
}
 
Example #4
Source File: ComponentScanAnnotationParser.java    From java-technology-stack with MIT License 5 votes vote down vote up
public ComponentScanAnnotationParser(Environment environment, ResourceLoader resourceLoader,
		BeanNameGenerator beanNameGenerator, BeanDefinitionRegistry registry) {

	this.environment = environment;
	this.resourceLoader = resourceLoader;
	this.beanNameGenerator = beanNameGenerator;
	this.registry = registry;
}
 
Example #5
Source File: ComponentScanAnnotationParser.java    From spring-analysis-note with MIT License 5 votes vote down vote up
public ComponentScanAnnotationParser(Environment environment, ResourceLoader resourceLoader,
		BeanNameGenerator beanNameGenerator, BeanDefinitionRegistry registry) {

	this.environment = environment;
	this.resourceLoader = resourceLoader;
	this.beanNameGenerator = beanNameGenerator;
	this.registry = registry;
}
 
Example #6
Source File: ClassPathBeanDefinitionScannerAgent.java    From HotswapAgent with GNU General Public License v2.0 5 votes vote down vote up
private ClassPathBeanDefinitionScannerAgent(ClassPathBeanDefinitionScanner scanner) {
    this.scanner = scanner;

    this.registry = scanner.getRegistry();
    this.scopeMetadataResolver = (ScopeMetadataResolver) ReflectionHelper.get(scanner, "scopeMetadataResolver");
    this.beanNameGenerator = (BeanNameGenerator) ReflectionHelper.get(scanner, "beanNameGenerator");
}
 
Example #7
Source File: ConfigurationClassBeanDefinitionReader.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Create a new {@link ConfigurationClassBeanDefinitionReader} instance
 * that will be used to populate the given {@link BeanDefinitionRegistry}.
 */
ConfigurationClassBeanDefinitionReader(BeanDefinitionRegistry registry, SourceExtractor sourceExtractor,
		ResourceLoader resourceLoader, Environment environment, BeanNameGenerator importBeanNameGenerator,
		ImportRegistry importRegistry) {

	this.registry = registry;
	this.sourceExtractor = sourceExtractor;
	this.resourceLoader = resourceLoader;
	this.environment = environment;
	this.importBeanNameGenerator = importBeanNameGenerator;
	this.importRegistry = importRegistry;
	this.conditionEvaluator = new ConditionEvaluator(registry, environment, resourceLoader);
}
 
Example #8
Source File: ConfigurationClassParser.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Create a new {@link ConfigurationClassParser} instance that will be used
 * to populate the set of configuration classes.
 */
public ConfigurationClassParser(MetadataReaderFactory metadataReaderFactory,
		ProblemReporter problemReporter, Environment environment, ResourceLoader resourceLoader,
		BeanNameGenerator componentScanBeanNameGenerator, BeanDefinitionRegistry registry) {

	this.metadataReaderFactory = metadataReaderFactory;
	this.problemReporter = problemReporter;
	this.environment = environment;
	this.resourceLoader = resourceLoader;
	this.registry = registry;
	this.componentScanParser = new ComponentScanAnnotationParser(
			environment, resourceLoader, componentScanBeanNameGenerator, registry);
	this.conditionEvaluator = new ConditionEvaluator(registry, environment, resourceLoader);
}
 
Example #9
Source File: ComponentScanBeanDefinitionParser.java    From spring-analysis-note with MIT License 5 votes vote down vote up
protected void parseBeanNameGenerator(Element element, ClassPathBeanDefinitionScanner scanner) {
	if (element.hasAttribute(NAME_GENERATOR_ATTRIBUTE)) {
		BeanNameGenerator beanNameGenerator = (BeanNameGenerator) instantiateUserDefinedStrategy(
				element.getAttribute(NAME_GENERATOR_ATTRIBUTE), BeanNameGenerator.class,
				scanner.getResourceLoader().getClassLoader());
		scanner.setBeanNameGenerator(beanNameGenerator);
	}
}
 
Example #10
Source File: PluginMybatisMapperProcessor.java    From springboot-plugin-framework-parent with Apache License 2.0 5 votes vote down vote up
@Override
public void registry(PluginRegistryInfo pluginRegistryInfo) throws Exception {
    if(!mybatisExist()){
        return;
    }
    List<Class<?>> groupClasses = pluginRegistryInfo.getGroupClasses(PluginMapperGroup.KEY);
    if(groupClasses == null || groupClasses.isEmpty()){
        return;
    }
    BasePlugin basePlugin = pluginRegistryInfo.getBasePlugin();
    String pluginId = pluginRegistryInfo.getPluginWrapper().getPluginId();
    Set<String> beanNames = new HashSet<>();
    for (Class<?> groupClass : groupClasses) {
        if (groupClass == null) {
            continue;
        }
        BeanNameGenerator beanNameGenerator = new PluginAnnotationBeanNameGenerator(basePlugin.getWrapper().getPluginId());
        AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(groupClass);
        ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(abd);
        abd.setScope(scopeMetadata.getScopeName());
        String beanName = beanNameGenerator.generateBeanName(abd, applicationContext);
        BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName);
        AnnotationConfigUtils.processCommonDefinitionAnnotations(abd);
        BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, applicationContext);
        mybatisInjectWrapper.processBeanDefinitions(definitionHolder, groupClass);
        beanNames.add(beanName);
        PluginInfoContainer.addRegisterBeanName(pluginId, beanName);
    }
    pluginRegistryInfo.addProcessorInfo(KEY, beanNames);
}
 
Example #11
Source File: ConfigurationClassParser.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Create a new {@link ConfigurationClassParser} instance that will be used
 * to populate the set of configuration classes.
 */
public ConfigurationClassParser(MetadataReaderFactory metadataReaderFactory,
		ProblemReporter problemReporter, Environment environment, ResourceLoader resourceLoader,
		BeanNameGenerator componentScanBeanNameGenerator, BeanDefinitionRegistry registry) {

	this.metadataReaderFactory = metadataReaderFactory;
	this.problemReporter = problemReporter;
	this.environment = environment;
	this.resourceLoader = resourceLoader;
	this.registry = registry;
	this.componentScanParser = new ComponentScanAnnotationParser(
			environment, resourceLoader, componentScanBeanNameGenerator, registry);
	this.conditionEvaluator = new ConditionEvaluator(registry, environment, resourceLoader);
}
 
Example #12
Source File: ConfigurationClassBeanDefinitionReader.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new {@link ConfigurationClassBeanDefinitionReader} instance that will be used
 * to populate the given {@link BeanDefinitionRegistry}.
 */
ConfigurationClassBeanDefinitionReader(BeanDefinitionRegistry registry, SourceExtractor sourceExtractor,
		ResourceLoader resourceLoader, Environment environment, BeanNameGenerator importBeanNameGenerator,
		ImportRegistry importRegistry) {

	this.registry = registry;
	this.sourceExtractor = sourceExtractor;
	this.resourceLoader = resourceLoader;
	this.environment = environment;
	this.importBeanNameGenerator = importBeanNameGenerator;
	this.importRegistry = importRegistry;
	this.conditionEvaluator = new ConditionEvaluator(registry, environment, resourceLoader);
}
 
Example #13
Source File: ComponentScanBeanDefinitionParser.java    From java-technology-stack with MIT License 5 votes vote down vote up
protected void parseBeanNameGenerator(Element element, ClassPathBeanDefinitionScanner scanner) {
	if (element.hasAttribute(NAME_GENERATOR_ATTRIBUTE)) {
		BeanNameGenerator beanNameGenerator = (BeanNameGenerator) instantiateUserDefinedStrategy(
				element.getAttribute(NAME_GENERATOR_ATTRIBUTE), BeanNameGenerator.class,
				scanner.getResourceLoader().getClassLoader());
		scanner.setBeanNameGenerator(beanNameGenerator);
	}
}
 
Example #14
Source File: ConfigurationClassBeanDefinitionReader.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Create a new {@link ConfigurationClassBeanDefinitionReader} instance
 * that will be used to populate the given {@link BeanDefinitionRegistry}.
 */
ConfigurationClassBeanDefinitionReader(BeanDefinitionRegistry registry, SourceExtractor sourceExtractor,
		ResourceLoader resourceLoader, Environment environment, BeanNameGenerator importBeanNameGenerator,
		ImportRegistry importRegistry) {

	this.registry = registry;
	this.sourceExtractor = sourceExtractor;
	this.resourceLoader = resourceLoader;
	this.environment = environment;
	this.importBeanNameGenerator = importBeanNameGenerator;
	this.importRegistry = importRegistry;
	this.conditionEvaluator = new ConditionEvaluator(registry, environment, resourceLoader);
}
 
Example #15
Source File: ComponentScanBeanDefinitionParser.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
protected void parseBeanNameGenerator(Element element, ClassPathBeanDefinitionScanner scanner) {
	if (element.hasAttribute(NAME_GENERATOR_ATTRIBUTE)) {
		BeanNameGenerator beanNameGenerator = (BeanNameGenerator) instantiateUserDefinedStrategy(
				element.getAttribute(NAME_GENERATOR_ATTRIBUTE), BeanNameGenerator.class,
				scanner.getResourceLoader().getClassLoader());
		scanner.setBeanNameGenerator(beanNameGenerator);
	}
}
 
Example #16
Source File: ComponentScanAnnotationParser.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
public ComponentScanAnnotationParser(ResourceLoader resourceLoader, Environment environment,
		BeanNameGenerator beanNameGenerator, BeanDefinitionRegistry registry) {

	this.resourceLoader = resourceLoader;
	this.environment = environment;
	this.beanNameGenerator = beanNameGenerator;
	this.registry = registry;
}
 
Example #17
Source File: ConfigurationClassParser.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new {@link ConfigurationClassParser} instance that will be used
 * to populate the set of configuration classes.
 */
public ConfigurationClassParser(MetadataReaderFactory metadataReaderFactory,
		ProblemReporter problemReporter, Environment environment, ResourceLoader resourceLoader,
		BeanNameGenerator componentScanBeanNameGenerator, BeanDefinitionRegistry registry) {

	this.metadataReaderFactory = metadataReaderFactory;
	this.problemReporter = problemReporter;
	this.environment = environment;
	this.resourceLoader = resourceLoader;
	this.registry = registry;
	this.componentScanParser = new ComponentScanAnnotationParser(
			resourceLoader, environment, componentScanBeanNameGenerator, registry);
	this.conditionEvaluator = new ConditionEvaluator(registry, environment, resourceLoader);
}
 
Example #18
Source File: ConfigurationClassBeanDefinitionReader.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Create a new {@link ConfigurationClassBeanDefinitionReader} instance that will be used
 * to populate the given {@link BeanDefinitionRegistry}.
 */
ConfigurationClassBeanDefinitionReader(BeanDefinitionRegistry registry, SourceExtractor sourceExtractor,
		ResourceLoader resourceLoader, Environment environment, BeanNameGenerator importBeanNameGenerator,
		ImportRegistry importRegistry) {

	this.registry = registry;
	this.sourceExtractor = sourceExtractor;
	this.resourceLoader = resourceLoader;
	this.environment = environment;
	this.importBeanNameGenerator = importBeanNameGenerator;
	this.importRegistry = importRegistry;
	this.conditionEvaluator = new ConditionEvaluator(registry, environment, resourceLoader);
}
 
Example #19
Source File: ComponentScanBeanDefinitionParser.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
protected void parseBeanNameGenerator(Element element, ClassPathBeanDefinitionScanner scanner) {
	if (element.hasAttribute(NAME_GENERATOR_ATTRIBUTE)) {
		BeanNameGenerator beanNameGenerator = (BeanNameGenerator) instantiateUserDefinedStrategy(
				element.getAttribute(NAME_GENERATOR_ATTRIBUTE), BeanNameGenerator.class,
				scanner.getResourceLoader().getClassLoader());
		scanner.setBeanNameGenerator(beanNameGenerator);
	}
}
 
Example #20
Source File: ComponentScanAnnotationParser.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public ComponentScanAnnotationParser(Environment environment, ResourceLoader resourceLoader,
		BeanNameGenerator beanNameGenerator, BeanDefinitionRegistry registry) {

	this.environment = environment;
	this.resourceLoader = resourceLoader;
	this.beanNameGenerator = beanNameGenerator;
	this.registry = registry;
}
 
Example #21
Source File: ConfigurationClassParser.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Create a new {@link ConfigurationClassParser} instance that will be used
 * to populate the set of configuration classes.
 */
public ConfigurationClassParser(MetadataReaderFactory metadataReaderFactory,
		ProblemReporter problemReporter, Environment environment, ResourceLoader resourceLoader,
		BeanNameGenerator componentScanBeanNameGenerator, BeanDefinitionRegistry registry) {

	this.metadataReaderFactory = metadataReaderFactory;
	this.problemReporter = problemReporter;
	this.environment = environment;
	this.resourceLoader = resourceLoader;
	this.registry = registry;
	this.componentScanParser = new ComponentScanAnnotationParser(
			environment, resourceLoader, componentScanBeanNameGenerator, registry);
	this.conditionEvaluator = new ConditionEvaluator(registry, environment, resourceLoader);
}
 
Example #22
Source File: AnnotationConfigWebApplicationContext.java    From java-technology-stack with MIT License 4 votes vote down vote up
/**
 * 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.isDebugEnabled()) {
			logger.debug("Registering annotated classes: [" +
					StringUtils.collectionToCommaDelimitedString(this.annotatedClasses) + "]");
		}
		reader.register(ClassUtils.toClassArray(this.annotatedClasses));
	}

	if (!this.basePackages.isEmpty()) {
		if (logger.isDebugEnabled()) {
			logger.debug("Scanning base packages: [" +
					StringUtils.collectionToCommaDelimitedString(this.basePackages) + "]");
		}
		scanner.scan(StringUtils.toStringArray(this.basePackages));
	}

	String[] configLocations = getConfigLocations();
	if (configLocations != null) {
		for (String configLocation : configLocations) {
			try {
				Class<?> clazz = ClassUtils.forName(configLocation, getClassLoader());
				if (logger.isTraceEnabled()) {
					logger.trace("Registering [" + configLocation + "]");
				}
				reader.register(clazz);
			}
			catch (ClassNotFoundException ex) {
				if (logger.isTraceEnabled()) {
					logger.trace("Could not load class for config location [" + configLocation +
							"] - trying package scan. " + ex);
				}
				int count = scanner.scan(configLocation);
				if (count == 0 && logger.isDebugEnabled()) {
					logger.debug("No annotated classes found for specified class/package [" + configLocation + "]");
				}
			}
		}
	}
}
 
Example #23
Source File: FeignClientToDubboProviderBeanPostProcessor.java    From spring-cloud-alibaba-dubbo with Apache License 2.0 4 votes vote down vote up
/**
 * Finds a {@link Set} of {@link BeanDefinitionHolder BeanDefinitionHolders} whose bean type annotated
 * {@link Service} Annotation.
 *
 * @param scanner       {@link ClassPathBeanDefinitionScanner}
 * @param packageToScan pachage to scan
 * @param registry      {@link BeanDefinitionRegistry}
 * @return non-null
 * @since 2.5.8
 */
private Set<BeanDefinitionHolder> findServiceBeanDefinitionHolders(
        ClassPathBeanDefinitionScanner scanner, String packageToScan, BeanDefinitionRegistry registry,
        BeanNameGenerator beanNameGenerator) {

    Set<BeanDefinition> beanDefinitions = scanner.findCandidateComponents(packageToScan);

    Set<BeanDefinitionHolder> beanDefinitionHolders = new LinkedHashSet<BeanDefinitionHolder>(beanDefinitions.size());

    for (BeanDefinition beanDefinition : beanDefinitions) {

        String beanName = beanNameGenerator.generateBeanName(beanDefinition, registry);
        BeanDefinitionHolder beanDefinitionHolder = new BeanDefinitionHolder(beanDefinition, beanName);
        beanDefinitionHolders.add(beanDefinitionHolder);

    }

    return beanDefinitionHolders;

}
 
Example #24
Source File: FeignClientToDubboProviderBeanPostProcessor.java    From spring-cloud-dubbo with Apache License 2.0 4 votes vote down vote up
/**
 * Finds a {@link Set} of {@link BeanDefinitionHolder BeanDefinitionHolders} whose bean type annotated
 * {@link Service} Annotation.
 *
 * @param scanner       {@link ClassPathBeanDefinitionScanner}
 * @param packageToScan pachage to scan
 * @param registry      {@link BeanDefinitionRegistry}
 * @return non-null
 * @since 2.5.8
 */
private Set<BeanDefinitionHolder> findServiceBeanDefinitionHolders(
        ClassPathBeanDefinitionScanner scanner, String packageToScan, BeanDefinitionRegistry registry,
        BeanNameGenerator beanNameGenerator) {

    Set<BeanDefinition> beanDefinitions = scanner.findCandidateComponents(packageToScan);

    Set<BeanDefinitionHolder> beanDefinitionHolders = new LinkedHashSet<BeanDefinitionHolder>(beanDefinitions.size());

    for (BeanDefinition beanDefinition : beanDefinitions) {

        String beanName = beanNameGenerator.generateBeanName(beanDefinition, registry);
        BeanDefinitionHolder beanDefinitionHolder = new BeanDefinitionHolder(beanDefinition, beanName);
        beanDefinitionHolders.add(beanDefinitionHolder);

    }

    return beanDefinitionHolders;

}
 
Example #25
Source File: AnnotatedBeanDefinitionRegistryUtils.java    From spring-context-support with Apache License 2.0 4 votes vote down vote up
/**
 * Finds a {@link Set} of {@link BeanDefinitionHolder BeanDefinitionHolders}
 *
 * @param scanner           {@link ClassPathBeanDefinitionScanner}
 * @param packageToScan     package to scan
 * @param registry          {@link BeanDefinitionRegistry}
 * @param beanNameGenerator {@link BeanNameGenerator}
 * @return non-null
 */
public static Set<BeanDefinitionHolder> findBeanDefinitionHolders(ClassPathBeanDefinitionScanner scanner,
                                                                  String packageToScan,
                                                                  BeanDefinitionRegistry registry,
                                                                  BeanNameGenerator beanNameGenerator) {

    Set<BeanDefinition> beanDefinitions = scanner.findCandidateComponents(packageToScan);

    Set<BeanDefinitionHolder> beanDefinitionHolders = new LinkedHashSet<BeanDefinitionHolder>(beanDefinitions.size());

    for (BeanDefinition beanDefinition : beanDefinitions) {

        String beanName = beanNameGenerator.generateBeanName(beanDefinition, registry);
        BeanDefinitionHolder beanDefinitionHolder = new BeanDefinitionHolder(beanDefinition, beanName);
        beanDefinitionHolders.add(beanDefinitionHolder);

    }

    return beanDefinitionHolders;

}
 
Example #26
Source File: ServiceAnnotationBeanPostProcessor.java    From dubbo-2.6.5 with Apache License 2.0 4 votes vote down vote up
/**
     * Registers Beans whose classes was annotated {@link Service} 注册类为带注释服务的bean
     *
     * @param packagesToScan The base packages to scan
     * @param registry       {@link BeanDefinitionRegistry}
     */
    private void registerServiceBeans(Set<String> packagesToScan, BeanDefinitionRegistry registry) {

//        创建dubbo服务类bean定义扫描器
        DubboClassPathBeanDefinitionScanner scanner =
                new DubboClassPathBeanDefinitionScanner(registry, environment, resourceLoader);

//        解析beanName解析器=》
        BeanNameGenerator beanNameGenerator = resolveBeanNameGenerator(registry);

        scanner.setBeanNameGenerator(beanNameGenerator);

//        扫描直接@Service
        scanner.addIncludeFilter(new AnnotationTypeFilter(Service.class));

        for (String packageToScan : packagesToScan) {

            // Registers @Service Bean first 扫描@Service注解的bean=》
            scanner.scan(packageToScan);

            // Finds all BeanDefinitionHolders of @Service whether @ComponentScan scans or not. 查找@ComponentScan指定的包路径下带有@Service的bean的bean定义=》
            Set<BeanDefinitionHolder> beanDefinitionHolders =
                    findServiceBeanDefinitionHolders(scanner, packageToScan, registry, beanNameGenerator);

            if (!CollectionUtils.isEmpty(beanDefinitionHolders)) {

                for (BeanDefinitionHolder beanDefinitionHolder : beanDefinitionHolders) {
//                    注册service bean=》
                    registerServiceBean(beanDefinitionHolder, registry, scanner);
                }

                if (logger.isInfoEnabled()) {
                    logger.info(beanDefinitionHolders.size() + " annotated Dubbo's @Service Components { " +
                            beanDefinitionHolders +
                            " } were scanned under package[" + packageToScan + "]");
                }

            } else {

                if (logger.isWarnEnabled()) {
                    logger.warn("No Spring Bean annotating Dubbo's @Service was found under package["
                            + packageToScan + "]");
                }

            }

        }

    }
 
Example #27
Source File: AnnotationConfigWebApplicationContext.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * 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 + "]");
					}
				}
			}
		}
	}
}
 
Example #28
Source File: AnnotatedBeanDefinitionReader.java    From spring-analysis-note with MIT License 4 votes vote down vote up
/**
 * Set the BeanNameGenerator to use for detected bean classes.
 * <p>The default is a {@link AnnotationBeanNameGenerator}.
 */
public void setBeanNameGenerator(@Nullable BeanNameGenerator beanNameGenerator) {
	this.beanNameGenerator =
			(beanNameGenerator != null ? beanNameGenerator : AnnotationBeanNameGenerator.INSTANCE);
}
 
Example #29
Source File: ServiceAnnotationBeanPostProcessor.java    From dubbo-2.6.5 with Apache License 2.0 4 votes vote down vote up
/**
 * Finds a {@link Set} of {@link BeanDefinitionHolder BeanDefinitionHolders} whose bean type annotated
 * {@link Service} Annotation.找到一组beandefinitionholder,其bean类型注释了服务注释。
 *
 * @param scanner       {@link ClassPathBeanDefinitionScanner}
 * @param packageToScan pachage to scan
 * @param registry      {@link BeanDefinitionRegistry}
 * @return non-null
 * @since 2.5.8
 */
private Set<BeanDefinitionHolder> findServiceBeanDefinitionHolders(
        ClassPathBeanDefinitionScanner scanner, String packageToScan, BeanDefinitionRegistry registry,
        BeanNameGenerator beanNameGenerator) {

    Set<BeanDefinition> beanDefinitions = scanner.findCandidateComponents(packageToScan);

    Set<BeanDefinitionHolder> beanDefinitionHolders = new LinkedHashSet<BeanDefinitionHolder>(beanDefinitions.size());

    for (BeanDefinition beanDefinition : beanDefinitions) {

        String beanName = beanNameGenerator.generateBeanName(beanDefinition, registry);
        BeanDefinitionHolder beanDefinitionHolder = new BeanDefinitionHolder(beanDefinition, beanName);
        beanDefinitionHolders.add(beanDefinitionHolder);

    }

    return beanDefinitionHolders;

}
 
Example #30
Source File: AnnotationConfigWebApplicationContext.java    From java-technology-stack with MIT License 4 votes vote down vote up
/**
 * Return the custom {@link BeanNameGenerator} for use with {@link AnnotatedBeanDefinitionReader}
 * and/or {@link ClassPathBeanDefinitionScanner}, if any.
 */
@Nullable
protected BeanNameGenerator getBeanNameGenerator() {
	return this.beanNameGenerator;
}