org.springframework.context.annotation.ScopeMetadataResolver#org.springframework.beans.factory.annotation.AnnotatedBeanDefinition源码实例Demo

下面列出了org.springframework.context.annotation.ScopeMetadataResolver#org.springframework.beans.factory.annotation.AnnotatedBeanDefinition 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

static void processCommonDefinitionAnnotations(AnnotatedBeanDefinition abd, AnnotatedTypeMetadata metadata) {
	if (metadata.isAnnotated(Lazy.class.getName())) {
		abd.setLazyInit(attributesFor(metadata, Lazy.class).getBoolean("value"));
	}
	else if (abd.getMetadata() != metadata && abd.getMetadata().isAnnotated(Lazy.class.getName())) {
		abd.setLazyInit(attributesFor(abd.getMetadata(), Lazy.class).getBoolean("value"));
	}

	if (metadata.isAnnotated(Primary.class.getName())) {
		abd.setPrimary(true);
	}
	if (metadata.isAnnotated(DependsOn.class.getName())) {
		abd.setDependsOn(attributesFor(metadata, DependsOn.class).getStringArray("value"));
	}

	if (abd instanceof AbstractBeanDefinition) {
		AbstractBeanDefinition absBd = (AbstractBeanDefinition) abd;
		if (metadata.isAnnotated(Role.class.getName())) {
			absBd.setRole(attributesFor(metadata, Role.class).getNumber("value").intValue());
		}
		if (metadata.isAnnotated(Description.class.getName())) {
			absBd.setDescription(attributesFor(metadata, Description.class).getString("value"));
		}
	}
}
 
/**
 * Derive a bean name from one of the annotations on the class.
 * @param annotatedDef the annotation-aware bean definition
 * @return the bean name, or {@code null} if none is found
 */
protected String determineBeanNameFromAnnotation(AnnotatedBeanDefinition annotatedDef) {
	AnnotationMetadata amd = annotatedDef.getMetadata();
	Set<String> types = amd.getAnnotationTypes();
	String beanName = null;
	for (String type : types) {
		AnnotationAttributes attributes = AnnotationConfigUtils.attributesFor(amd, type);
		if (isStereotypeWithNameValue(type, amd.getMetaAnnotationTypes(type), attributes)) {
			Object value = attributes.get("value");
			if (value instanceof String) {
				String strVal = (String) value;
				if (StringUtils.hasLength(strVal)) {
					if (beanName != null && !strVal.equals(beanName)) {
						throw new IllegalStateException("Stereotype annotations suggest inconsistent " +
								"component names: '" + beanName + "' versus '" + strVal + "'");
					}
					beanName = strVal;
				}
			}
		}
	}
	return beanName;
}
 
/**
 * Gets the annotation attributes {@link RestTemplate} bean being annotated
 * {@link DubboTransported @DubboTransported}.
 * @param beanName the bean name of {@link LoadBalanced @LoadBalanced}
 * {@link RestTemplate}
 * @param attributesResolver {@link DubboTransportedAttributesResolver}
 * @return non-null {@link Map}
 */
private Map<String, Object> getDubboTranslatedAttributes(String beanName,
		DubboTransportedAttributesResolver attributesResolver) {
	Map<String, Object> attributes = Collections.emptyMap();
	BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName);
	if (beanDefinition instanceof AnnotatedBeanDefinition) {
		AnnotatedBeanDefinition annotatedBeanDefinition = (AnnotatedBeanDefinition) beanDefinition;
		MethodMetadata factoryMethodMetadata = annotatedBeanDefinition
				.getFactoryMethodMetadata();
		attributes = factoryMethodMetadata != null ? Optional
				.ofNullable(factoryMethodMetadata
						.getAnnotationAttributes(DUBBO_TRANSPORTED_CLASS_NAME))
				.orElse(attributes) : Collections.emptyMap();
	}
	return attributesResolver.resolve(attributes);
}
 
/**
 * Derive a bean name from one of the annotations on the class.
 * @param annotatedDef the annotation-aware bean definition
 * @return the bean name, or {@code null} if none is found
 */
@Nullable
protected String determineBeanNameFromAnnotation(AnnotatedBeanDefinition annotatedDef) {
	AnnotationMetadata amd = annotatedDef.getMetadata();
	Set<String> types = amd.getAnnotationTypes();
	String beanName = null;
	for (String type : types) {
		AnnotationAttributes attributes = AnnotationConfigUtils.attributesFor(amd, type);
		if (attributes != null && isStereotypeWithNameValue(type, amd.getMetaAnnotationTypes(type), attributes)) {
			Object value = attributes.get("value");
			if (value instanceof String) {
				String strVal = (String) value;
				if (StringUtils.hasLength(strVal)) {
					if (beanName != null && !strVal.equals(beanName)) {
						throw new IllegalStateException("Stereotype annotations suggest inconsistent " +
								"component names: '" + beanName + "' versus '" + strVal + "'");
					}
					beanName = strVal;
				}
			}
		}
	}
	return beanName;
}
 
源代码5 项目: JGiven   文件: JGivenBeanFactoryPostProcessor.java
@Override
public void postProcessBeanFactory( ConfigurableListableBeanFactory beanFactory ) throws BeansException {
    String[] beanNames = beanFactory.getBeanDefinitionNames();
    for( String beanName : beanNames ) {
        if( beanFactory.containsBeanDefinition( beanName ) ) {
            BeanDefinition beanDefinition = beanFactory.getBeanDefinition( beanName );
            if( beanDefinition instanceof AnnotatedBeanDefinition ) {
                AnnotatedBeanDefinition annotatedBeanDefinition = (AnnotatedBeanDefinition) beanDefinition;
                if( annotatedBeanDefinition.getMetadata().hasAnnotation( JGivenStage.class.getName() ) ) {
                    String className = beanDefinition.getBeanClassName();
                    Class<?> stageClass = createStageClass( beanName, className );
                    beanDefinition.setBeanClassName( stageClass.getName() );
                }
            }
        }
    }
}
 
源代码6 项目: lams   文件: AnnotationConfigUtils.java
static void processCommonDefinitionAnnotations(AnnotatedBeanDefinition abd, AnnotatedTypeMetadata metadata) {
	if (metadata.isAnnotated(Lazy.class.getName())) {
		abd.setLazyInit(attributesFor(metadata, Lazy.class).getBoolean("value"));
	}
	else if (abd.getMetadata() != metadata && abd.getMetadata().isAnnotated(Lazy.class.getName())) {
		abd.setLazyInit(attributesFor(abd.getMetadata(), Lazy.class).getBoolean("value"));
	}

	if (metadata.isAnnotated(Primary.class.getName())) {
		abd.setPrimary(true);
	}
	if (metadata.isAnnotated(DependsOn.class.getName())) {
		abd.setDependsOn(attributesFor(metadata, DependsOn.class).getStringArray("value"));
	}

	if (abd instanceof AbstractBeanDefinition) {
		AbstractBeanDefinition absBd = (AbstractBeanDefinition) abd;
		if (metadata.isAnnotated(Role.class.getName())) {
			absBd.setRole(attributesFor(metadata, Role.class).getNumber("value").intValue());
		}
		if (metadata.isAnnotated(Description.class.getName())) {
			absBd.setDescription(attributesFor(metadata, Description.class).getString("value"));
		}
	}
}
 
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
	ClassPathScanningCandidateComponentProvider scanner = new ScanningComponent(Boolean.FALSE, this.environment);
	scanner.setResourceLoader(this.resourceLoader);

	AnnotationTypeFilter annotationTypeFilter = new AnnotationTypeFilter(Network.class);
	scanner.addIncludeFilter(annotationTypeFilter);

	String packageName = ClassUtils.getPackageName(importingClassMetadata.getClassName());
	Set<BeanDefinition> candidateComponents = scanner.findCandidateComponents(packageName);
	candidateComponents.forEach(beanDefinition -> {
		AnnotatedBeanDefinition annotatedBeanDefinition = (AnnotatedBeanDefinition) beanDefinition;
		AnnotationMetadata annotationMetadata = annotatedBeanDefinition.getMetadata();
		BeanDefinitionBuilder definition = BeanDefinitionBuilder.genericBeanDefinition(NetworkFactory.class);
		String className = annotationMetadata.getClassName();
		definition.addPropertyValue(NetworkFactoryConstants.PROPERTY_VALUE.getValue(), className);
		definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);

		AbstractBeanDefinition abstractBeanDefinition = definition.getBeanDefinition();
		BeanDefinitionHolder holder = new BeanDefinitionHolder(abstractBeanDefinition, className);
		BeanDefinitionReaderUtils.registerBeanDefinition(holder, registry);

	});

}
 
源代码8 项目: BootNettyRpc   文件: NettyRpcRegistrar.java
protected ClassPathScanningCandidateComponentProvider getScanner() {

        return new ClassPathScanningCandidateComponentProvider( false, this.environment ) {

            @Override
            protected boolean isCandidateComponent(
                    AnnotatedBeanDefinition beanDefinition) {
                if (beanDefinition.getMetadata().isIndependent()) {

                    if (beanDefinition.getMetadata().isInterface() && beanDefinition.getMetadata().getInterfaceNames().length == 1
                            && Annotation.class.getName().equals( beanDefinition.getMetadata().getInterfaceNames()[0] )) {
                        try {
                            Class<?> target = ClassUtils.forName( beanDefinition.getMetadata().getClassName(), NettyRpcRegistrar.this.classLoader );
                            return !target.isAnnotation();
                        } catch (Exception ex) {
                            this.logger.error( "Could not load target class: " + beanDefinition.getMetadata().getClassName(), ex );

                        }
                    }
                    return true;
                }
                return false;

            }
        };
    }
 
public Set<BeanDefinitionHolder> doScan(String... basePackages) {
  Assert.notEmpty(basePackages, "At least one base package must be specified");
  Set<BeanDefinitionHolder> beanDefinitions = new LinkedHashSet<>();
  for (String basePackage : basePackages) {
    Set<BeanDefinition> candidates = findCandidateComponents(basePackage);
    for (BeanDefinition candidate : candidates) {
      ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(candidate);
      candidate.setScope(scopeMetadata.getScopeName());
      String beanName = this.beanNameGenerator.generateBeanName(candidate, this.getRegistry());
      if (candidate instanceof AbstractBeanDefinition) {
        postProcessBeanDefinition((AbstractBeanDefinition) candidate, beanName);
      }
      if (candidate instanceof AnnotatedBeanDefinition) {
        AnnotationConfigUtils.processCommonDefinitionAnnotations((AnnotatedBeanDefinition) candidate);
      }
      if (checkCandidate(beanName, candidate)) {
        BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(candidate, beanName);
        beanDefinitions.add(definitionHolder);
      }
    }
  }
  return beanDefinitions;
}
 
/**
 * Derive a bean name from one of the annotations on the class.
 *
 * @param annotatedDef the annotation-aware bean definition
 * @return the bean name, or {@code null} if none is found
 */
protected String determineBeanNameFromAnnotation(AnnotatedBeanDefinition annotatedDef) {
    AnnotationMetadata amd = annotatedDef.getMetadata();
    Set<String> types = amd.getAnnotationTypes();
    String beanName = null;
    for (String type : types) {
        AnnotationAttributes attributes = AnnotationConfigUtils.attributesFor(amd, type);
        if (isStereotypeWithNameValue(type, amd.getMetaAnnotationTypes(type), attributes)) {
            Object value = attributes.get("value");
            if (value instanceof String) {
                String strVal = (String) value;
                if (StringUtils.hasLength(strVal)) {
                    if (beanName != null && !strVal.equals(beanName)) {
                        throw new IllegalStateException("Stereotype annotations suggest inconsistent " +
                                "component names: '" + beanName + "' versus '" + strVal + "'");
                    }
                    beanName = strVal;
                }
            }
        }
    }
    return beanName;
}
 
private void registerNettyRpcClient(AnnotatedBeanDefinition beanDefinition,BeanDefinitionRegistry registry)  {
    AnnotationMetadata metadata = beanDefinition.getMetadata();
    Map<String, Object> nettyRpcClientAttributes = metadata.getAnnotationAttributes(nettyRpcClientCanonicalName);
    Map<String, Object> lazyAttributes = metadata.getAnnotationAttributes(lazyCanonicalName);

    Class<?> beanClass;
    try {
        beanClass = ClassUtils.forName(metadata.getClassName(), classLoader);
    } catch (ClassNotFoundException e) {
        throw new BeanCreationException("NettyRpcClientsRegistrar failure! notfound class",e);
    }

    String serviceName = resolve((String) nettyRpcClientAttributes.get("serviceName"));
    beanDefinition.setLazyInit(lazyAttributes == null || Boolean.TRUE.equals(lazyAttributes.get("value")));
    ((AbstractBeanDefinition)beanDefinition).setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);
    ((AbstractBeanDefinition)beanDefinition).setInstanceSupplier(newInstanceSupplier(beanClass,serviceName,(int)nettyRpcClientAttributes.get("timeout")));

    String beanName = generateBeanName(beanDefinition.getBeanClassName());
    registry.registerBeanDefinition(beanName,beanDefinition);
}
 
源代码12 项目: lams   文件: AnnotationScopeMetadataResolver.java
@Override
public ScopeMetadata resolveScopeMetadata(BeanDefinition definition) {
	ScopeMetadata metadata = new ScopeMetadata();
	if (definition instanceof AnnotatedBeanDefinition) {
		AnnotatedBeanDefinition annDef = (AnnotatedBeanDefinition) definition;
		AnnotationAttributes attributes = AnnotationConfigUtils.attributesFor(
				annDef.getMetadata(), this.scopeAnnotationType);
		if (attributes != null) {
			metadata.setScopeName(attributes.getString("value"));
			ScopedProxyMode proxyMode = attributes.getEnum("proxyMode");
			if (proxyMode == null || proxyMode == ScopedProxyMode.DEFAULT) {
				proxyMode = this.defaultProxyMode;
			}
			metadata.setScopedProxyMode(proxyMode);
		}
	}
	return metadata;
}
 
@Override
protected Map<String, Object>[] resolveRuntimeAttributesArray(
		AnnotatedBeanDefinition beanDefinition, Properties globalNacosProperties) {
	// Get AnnotationMetadata
	AnnotationMetadata metadata = beanDefinition.getMetadata();

	Set<String> annotationTypes = metadata.getAnnotationTypes();

	List<Map<String, Object>> annotationAttributesList = new LinkedList<Map<String, Object>>();

	for (String annotationType : annotationTypes) {
		annotationAttributesList
				.addAll(getAnnotationAttributesList(metadata, annotationType));
	}

	return annotationAttributesList.toArray(new Map[0]);
}
 
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);
    }
 
@Test
public void customRequestScopeWithAttribute() {
	AnnotatedBeanDefinition bd = new AnnotatedGenericBeanDefinition(
		AnnotatedWithCustomRequestScopeWithAttributeOverride.class);
	ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(bd);
	assertNotNull("resolveScopeMetadata(..) must *never* return null.", scopeMetadata);
	assertEquals("request", scopeMetadata.getScopeName());
	assertEquals(TARGET_CLASS, scopeMetadata.getScopedProxyMode());
}
 
/**
 * Is present bean that was registered by the specified {@link Annotation annotated} {@link Class class}
 *
 * @param registry       {@link BeanDefinitionRegistry}
 * @param annotatedClass the {@link Annotation annotated} {@link Class class}
 * @return if present, return <code>true</code>, or <code>false</code>
 * @since 1.0.3
 */
public static boolean isPresentBean(BeanDefinitionRegistry registry, Class<?> annotatedClass) {

    boolean present = false;

    String[] beanNames = registry.getBeanDefinitionNames();

    ClassLoader classLoader = annotatedClass.getClassLoader();

    for (String beanName : beanNames) {
        BeanDefinition beanDefinition = registry.getBeanDefinition(beanName);
        if (beanDefinition instanceof AnnotatedBeanDefinition) {
            AnnotationMetadata annotationMetadata = ((AnnotatedBeanDefinition) beanDefinition).getMetadata();
            String className = annotationMetadata.getClassName();
            Class<?> targetClass = resolveClassName(className, classLoader);
            present = nullSafeEquals(targetClass, annotatedClass);
            if (present) {
                if (logger.isDebugEnabled()) {
                    logger.debug(format("The annotatedClass[class : %s , bean name : %s] was present in registry[%s]",
                            className, beanName, registry));
                }
                break;
            }
        }
    }

    return present;
}
 
@Test
public void customRequestScopeWithAttributeViaAsm() throws IOException {
	MetadataReaderFactory readerFactory = new SimpleMetadataReaderFactory();
	MetadataReader reader = readerFactory.getMetadataReader(AnnotatedWithCustomRequestScopeWithAttributeOverride.class.getName());
	AnnotatedBeanDefinition bd = new AnnotatedGenericBeanDefinition(reader.getAnnotationMetadata());
	ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(bd);
	assertNotNull("resolveScopeMetadata(..) must *never* return null.", scopeMetadata);
	assertEquals("request", scopeMetadata.getScopeName());
	assertEquals(TARGET_CLASS, scopeMetadata.getScopedProxyMode());
}
 
protected ClassPathScanningCandidateComponentProvider getScanner() {
    return new ClassPathScanningCandidateComponentProvider(false) {

        @Override
        protected boolean isCandidateComponent(
                AnnotatedBeanDefinition beanDefinition) {
            if (beanDefinition.getMetadata().isIndependent()) {
                // TODO until SPR-11711 will be resolved
                if (beanDefinition.getMetadata().isInterface()
                        && beanDefinition.getMetadata()
                        .getInterfaceNames().length == 1
                        && Annotation.class.getName().equals(beanDefinition
                        .getMetadata().getInterfaceNames()[0])) {
                    try {
                        Class<?> target = ClassUtils.forName(
                                beanDefinition.getMetadata().getClassName(),
                                Java110ListenerDiscoveryRegistrar.this.classLoader);
                        return !target.isAnnotation();
                    }
                    catch (Exception ex) {
                        this.logger.error(
                                "Could not load target class: "
                                        + beanDefinition.getMetadata().getClassName(),
                                ex);

                    }
                }
                return true;
            }
            return false;

        }
    };
}
 
/**
 * Perform a scan within the specified base packages,
 * returning the registered bean definitions.
 * <p>This method does <i>not</i> register an annotation config processor
 * but rather leaves this up to the caller.
 * @param basePackages the packages to check for annotated classes
 * @return set of beans registered if any for tooling registration purposes (never {@code null})
 */
protected Set<BeanDefinitionHolder> doScan(String... basePackages) {
	Assert.notEmpty(basePackages, "At least one base package must be specified");
	Set<BeanDefinitionHolder> beanDefinitions = new LinkedHashSet<>();
	for (String basePackage : basePackages) {
		Set<BeanDefinition> candidates = findCandidateComponents(basePackage);
		for (BeanDefinition candidate : candidates) {
			ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(candidate);
			candidate.setScope(scopeMetadata.getScopeName());
			String beanName = this.beanNameGenerator.generateBeanName(candidate, this.registry);
			if (candidate instanceof AbstractBeanDefinition) {
				postProcessBeanDefinition((AbstractBeanDefinition) candidate, beanName);
			}
			if (candidate instanceof AnnotatedBeanDefinition) {
				AnnotationConfigUtils.processCommonDefinitionAnnotations((AnnotatedBeanDefinition) candidate);
			}
			if (checkCandidate(beanName, candidate)) {
				BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(candidate, beanName);
				definitionHolder =
						AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
				beanDefinitions.add(definitionHolder);
				registerBeanDefinition(definitionHolder, this.registry);
			}
		}
	}
	return beanDefinitions;
}
 
@Test
public void resolveScopeMetadataShouldNotApplyScopedProxyModeToSingleton() {
	AnnotatedBeanDefinition bd = new AnnotatedGenericBeanDefinition(AnnotatedWithSingletonScope.class);
	ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(bd);
	assertNotNull("resolveScopeMetadata(..) must *never* return null.", scopeMetadata);
	assertEquals(BeanDefinition.SCOPE_SINGLETON, scopeMetadata.getScopeName());
	assertEquals(NO, scopeMetadata.getScopedProxyMode());
}
 
@Test
public void resolveScopeMetadataShouldReadScopedProxyModeFromAnnotation() {
	AnnotatedBeanDefinition bd = new AnnotatedGenericBeanDefinition(AnnotatedWithScopedProxy.class);
	ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(bd);
	assertNotNull("resolveScopeMetadata(..) must *never* return null.", scopeMetadata);
	assertEquals("request", scopeMetadata.getScopeName());
	assertEquals(TARGET_CLASS, scopeMetadata.getScopedProxyMode());
}
 
@Test
public void customRequestScope() {
	AnnotatedBeanDefinition bd = new AnnotatedGenericBeanDefinition(AnnotatedWithCustomRequestScope.class);
	ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(bd);
	assertNotNull("resolveScopeMetadata(..) must *never* return null.", scopeMetadata);
	assertEquals("request", scopeMetadata.getScopeName());
	assertEquals(NO, scopeMetadata.getScopedProxyMode());
}
 
@Test
public void customRequestScopeViaAsm() throws IOException {
	MetadataReaderFactory readerFactory = new SimpleMetadataReaderFactory();
	MetadataReader reader = readerFactory.getMetadataReader(AnnotatedWithCustomRequestScope.class.getName());
	AnnotatedBeanDefinition bd = new AnnotatedGenericBeanDefinition(reader.getAnnotationMetadata());
	ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(bd);
	assertNotNull("resolveScopeMetadata(..) must *never* return null.", scopeMetadata);
	assertEquals("request", scopeMetadata.getScopeName());
	assertEquals(NO, scopeMetadata.getScopedProxyMode());
}
 
@Test
public void generateBeanNameWithNamedComponentWhereTheNameIsBlank() {
	BeanDefinitionRegistry registry = new SimpleBeanDefinitionRegistry();
	AnnotatedBeanDefinition bd = new AnnotatedGenericBeanDefinition(ComponentWithBlankName.class);
	String beanName = this.beanNameGenerator.generateBeanName(bd, registry);
	assertNotNull("The generated beanName must *never* be null.", beanName);
	assertTrue("The generated beanName must *never* be blank.", StringUtils.hasText(beanName));
	String expectedGeneratedBeanName = this.beanNameGenerator.buildDefaultBeanName(bd);
	assertEquals(expectedGeneratedBeanName, beanName);
}
 
@Test
public void generateBeanNameWithAnonymousComponentYieldsGeneratedBeanName() {
	BeanDefinitionRegistry registry = new SimpleBeanDefinitionRegistry();
	AnnotatedBeanDefinition bd = new AnnotatedGenericBeanDefinition(AnonymousComponent.class);
	String beanName = this.beanNameGenerator.generateBeanName(bd, registry);
	assertNotNull("The generated beanName must *never* be null.", beanName);
	assertTrue("The generated beanName must *never* be blank.", StringUtils.hasText(beanName));
	String expectedGeneratedBeanName = this.beanNameGenerator.buildDefaultBeanName(bd);
	assertEquals(expectedGeneratedBeanName, beanName);
}
 
源代码26 项目: onetwo   文件: AbstractImportRegistrar.java
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
	Class<? extends Annotation> componentAnnoClass = getComponentAnnotationClass();
	List<BeanDefinition> beandefList = scanBeanDefinitions(importingClassMetadata);
	beandefList.stream().filter(AnnotatedBeanDefinition.class::isInstance)
					.forEach(bd->{
						AnnotatedBeanDefinition beanDefinition = (AnnotatedBeanDefinition) bd;
						AnnotationMetadata annotationMetadata = beanDefinition.getMetadata();
						Assert.isTrue(annotationMetadata.isInterface(),
								"@"+componentAnnoClass.getSimpleName()+" can only be specified on an interface");

						AnnotationAttributes tagAttributes = SpringUtils.getAnnotationAttributes(annotationMetadata, componentAnnoClass);
						registerComponent(registry, annotationMetadata, tagAttributes);
					});
}
 
@Test
public void generateBeanNameFromMetaComponentWithNonStringValue() {
	BeanDefinitionRegistry registry = new SimpleBeanDefinitionRegistry();
	AnnotatedBeanDefinition bd = new AnnotatedGenericBeanDefinition(ComponentFromNonStringMeta.class);
	String beanName = this.beanNameGenerator.generateBeanName(bd, registry);
	assertEquals("annotationBeanNameGeneratorTests.ComponentFromNonStringMeta", beanName);
}
 
@Test
public void generateBeanNameFromComposedControllerAnnotationWithoutName() {
	// SPR-11360
	BeanDefinitionRegistry registry = new SimpleBeanDefinitionRegistry();
	AnnotatedBeanDefinition bd = new AnnotatedGenericBeanDefinition(ComposedControllerAnnotationWithoutName.class);
	String beanName = this.beanNameGenerator.generateBeanName(bd, registry);
	String expectedGeneratedBeanName = this.beanNameGenerator.buildDefaultBeanName(bd);
	assertEquals(expectedGeneratedBeanName, beanName);
}
 
@Test
public void generateBeanNameFromComposedControllerAnnotationWithBlankName() {
	// SPR-11360
	BeanDefinitionRegistry registry = new SimpleBeanDefinitionRegistry();
	AnnotatedBeanDefinition bd = new AnnotatedGenericBeanDefinition(ComposedControllerAnnotationWithBlankName.class);
	String beanName = this.beanNameGenerator.generateBeanName(bd, registry);
	String expectedGeneratedBeanName = this.beanNameGenerator.buildDefaultBeanName(bd);
	assertEquals(expectedGeneratedBeanName, beanName);
}
 
@Test
public void generateBeanNameFromComposedControllerAnnotationWithStringValue() {
	// SPR-11360
	BeanDefinitionRegistry registry = new SimpleBeanDefinitionRegistry();
	AnnotatedBeanDefinition bd = new AnnotatedGenericBeanDefinition(
		ComposedControllerAnnotationWithStringValue.class);
	String beanName = this.beanNameGenerator.generateBeanName(bd, registry);
	assertEquals("restController", beanName);
}