Java Code Examples for org.springframework.beans.factory.support.BeanDefinitionReaderUtils

The following examples show how to use org.springframework.beans.factory.support.BeanDefinitionReaderUtils. These examples are extracted from open source projects. 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
/**
 * Process the given bean element, parsing the bean definition
 * and registering it with the registry.
 */
protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
	// 注释 1.15 解析 bean 名称的元素
	BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
	if (bdHolder != null) {
		bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
		try {
			// Register the final decorated instance. (注释 1.16 注册最后修饰后的实例)
			BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());
		}
		catch (BeanDefinitionStoreException ex) {
			getReaderContext().error("Failed to register bean definition with name '" +
					bdHolder.getBeanName() + "'", ele, ex);
		}
		// Send registration event. 通知相关的监听器,表示这个 bean 已经加载完成
		getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));
	}
}
 
Example 2
@Nullable
private BeanDefinitionHolder parseNestedCustomElement(Element ele, @Nullable BeanDefinition containingBd) {
	BeanDefinition innerDefinition = parseCustomElement(ele, containingBd);
	if (innerDefinition == null) {
		error("Incorrect usage of element '" + ele.getNodeName() + "' in a nested manner. " +
				"This tag cannot be used nested inside <property>.", ele);
		return null;
	}
	String id = ele.getNodeName() + BeanDefinitionReaderUtils.GENERATED_BEAN_NAME_SEPARATOR +
			ObjectUtils.getIdentityHexString(innerDefinition);
	if (logger.isTraceEnabled()) {
		logger.trace("Using generated bean name [" + id +
				"] for nested custom element '" + ele.getNodeName() + "'");
	}
	return new BeanDefinitionHolder(innerDefinition, id);
}
 
Example 3
Source Project: spring-analysis-note   Source File: BeanNameGenerationTests.java    License: MIT License 6 votes vote down vote up
@Test
public void naming() {
	String className = GeneratedNameBean.class.getName();

	String targetName = className + BeanDefinitionReaderUtils.GENERATED_BEAN_NAME_SEPARATOR + "0";
	GeneratedNameBean topLevel1 = (GeneratedNameBean) beanFactory.getBean(targetName);
	assertNotNull(topLevel1);

	targetName = className + BeanDefinitionReaderUtils.GENERATED_BEAN_NAME_SEPARATOR + "1";
	GeneratedNameBean topLevel2 = (GeneratedNameBean) beanFactory.getBean(targetName);
	assertNotNull(topLevel2);

	GeneratedNameBean child1 = topLevel1.getChild();
	assertNotNull(child1.getBeanName());
	assertTrue(child1.getBeanName().startsWith(className));

	GeneratedNameBean child2 = topLevel2.getChild();
	assertNotNull(child2.getBeanName());
	assertTrue(child2.getBeanName().startsWith(className));

	assertFalse(child1.getBeanName().equals(child2.getBeanName()));
}
 
Example 4
/**
 * Process the given bean element, parsing the bean definition
 * and registering it with the registry.
 */
protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
	BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
	if (bdHolder != null) {
		bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
		try {
			// Register the final decorated instance.
			BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());
		}
		catch (BeanDefinitionStoreException ex) {
			getReaderContext().error("Failed to register bean definition with name '" +
					bdHolder.getBeanName() + "'", ele, ex);
		}
		// Send registration event.
		getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));
	}
}
 
Example 5
@Nullable
private BeanDefinitionHolder parseNestedCustomElement(Element ele, @Nullable BeanDefinition containingBd) {
	BeanDefinition innerDefinition = parseCustomElement(ele, containingBd);
	if (innerDefinition == null) {
		error("Incorrect usage of element '" + ele.getNodeName() + "' in a nested manner. " +
				"This tag cannot be used nested inside <property>.", ele);
		return null;
	}
	String id = ele.getNodeName() + BeanDefinitionReaderUtils.GENERATED_BEAN_NAME_SEPARATOR +
			ObjectUtils.getIdentityHexString(innerDefinition);
	if (logger.isTraceEnabled()) {
		logger.trace("Using generated bean name [" + id +
				"] for nested custom element '" + ele.getNodeName() + "'");
	}
	return new BeanDefinitionHolder(innerDefinition, id);
}
 
Example 6
Source Project: java-technology-stack   Source File: BeanNameGenerationTests.java    License: MIT License 6 votes vote down vote up
@Test
public void naming() {
	String className = GeneratedNameBean.class.getName();

	String targetName = className + BeanDefinitionReaderUtils.GENERATED_BEAN_NAME_SEPARATOR + "0";
	GeneratedNameBean topLevel1 = (GeneratedNameBean) beanFactory.getBean(targetName);
	assertNotNull(topLevel1);

	targetName = className + BeanDefinitionReaderUtils.GENERATED_BEAN_NAME_SEPARATOR + "1";
	GeneratedNameBean topLevel2 = (GeneratedNameBean) beanFactory.getBean(targetName);
	assertNotNull(topLevel2);

	GeneratedNameBean child1 = topLevel1.getChild();
	assertNotNull(child1.getBeanName());
	assertTrue(child1.getBeanName().startsWith(className));

	GeneratedNameBean child2 = topLevel2.getChild();
	assertNotNull(child2.getBeanName());
	assertTrue(child2.getBeanName().startsWith(className));

	assertFalse(child1.getBeanName().equals(child2.getBeanName()));
}
 
Example 7
@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);

	});

}
 
Example 8
Source Project: spring-fu   Source File: WebMvcServerDsl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void initialize(GenericApplicationContext context) {
	super.initialize(context);
	this.dsl.accept(this);
	context.registerBean(BeanDefinitionReaderUtils.uniqueBeanName(RouterFunction.class.getName(), context), RouterFunction.class, () ->
		RouterFunctions.route().resources("/**", new ClassPathResource("static/")).build()
	);
	serverProperties.setPort(port);
	serverProperties.getServlet().setRegisterDefaultServlet(false);
	if (!convertersConfigured) {
		new StringConverterInitializer().initialize(context);
		new ResourceConverterInitializer().initialize(context);
	}
	if (context.containsBeanDefinition("webHandler")) {
		throw new IllegalStateException("Only one webFlux per application is supported");
	}
	new ServletWebServerInitializer(serverProperties, webMvcProperties, resourceProperties).initialize(context);
}
 
Example 9
Source Project: flower   Source File: DDDBeanRegistryPostProcessor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
  Set<String> serviceTypes = new HashSet<>();
  Class<?> services[] =
      new Class<?>[] {CommandHandlerService.class, EventHandlerService.class, QueryHandlerService.class,
          DDDStartService.class, DDDEndService.class, DefaultCommandGateway.class, DefaultQueryGateway.class};

  for (Class<?> service : services) {
    BeanDefinition beanDefinition = new RootBeanDefinition(service);
    String handlerServiceName = BeanDefinitionReaderUtils.generateBeanName(beanDefinition, registry);
    registry.registerBeanDefinition(handlerServiceName, beanDefinition);
    if (Service.class.isAssignableFrom(service)) {
      serviceTypes.add(service.getName());
    }
  }

  final String dddFactoryName = "dddFactory";
  if (registry.containsBeanDefinition(dddFactoryName)) {
    BeanDefinition dddFactoryBeanDefinition = registry.getBeanDefinition(dddFactoryName);
    dddFactoryBeanDefinition.getPropertyValues().add("serviceTypes", serviceTypes);
  }

}
 
Example 10
/**
 * 设置注册bean动态AOP信息
 *
 * @param configs
 * @param beanFactory
 */
private void setAopInfo(List<String> configs, ConfigurableListableBeanFactory beanFactory) {

    if (beanFactory instanceof BeanDefinitionRegistry) {
        BeanDefinitionRegistry beanDefinitionRegistry = (BeanDefinitionRegistry) beanFactory;
        for (String config : configs) {
            //增强器
            RootBeanDefinition advisor = new RootBeanDefinition(DefaultBeanFactoryPointcutAdvisor.class);
            advisor.getPropertyValues().addPropertyValue("adviceBeanName", new RuntimeBeanReference("httpParamsValidateAdvisor").getBeanName());
            //切点类
            RootBeanDefinition pointCut = new RootBeanDefinition(AspectJExpressionPointcut.class);
            pointCut.setScope(BeanDefinition.SCOPE_PROTOTYPE);
            pointCut.setSynthetic(true);
            pointCut.getPropertyValues().addPropertyValue("expression", config);

            advisor.getPropertyValues().addPropertyValue("pointcut", pointCut);
            //注册到spring容器
            String beanName = BeanDefinitionReaderUtils.generateBeanName(advisor, beanDefinitionRegistry, false);
            beanDefinitionRegistry.registerBeanDefinition(beanName, advisor);
        }
    }

}
 
Example 11
/**
 * Process the given bean element, parsing the bean definition
 * and registering it with the registry.
 */
protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
	BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
	if (bdHolder != null) {
		bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
		try {
			// Register the final decorated instance.
			BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());
		}
		catch (BeanDefinitionStoreException ex) {
			getReaderContext().error("Failed to register bean definition with name '" +
					bdHolder.getBeanName() + "'", ele, ex);
		}
		// Send registration event.
		getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));
	}
}
 
Example 12
/**
 * Process the given bean element, parsing the bean definition
 * and registering it with the registry.
 */
protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
	BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
	if (bdHolder != null) {
		bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
		try {
			// Register the final decorated instance.
			BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());
		}
		catch (BeanDefinitionStoreException ex) {
			getReaderContext().error("Failed to register bean definition with name '" +
					bdHolder.getBeanName() + "'", ele, ex);
		}
		// Send registration event.
		getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));
	}
}
 
Example 13
Source Project: tephra   Source File: ClassReloaderImpl.java    License: MIT License 6 votes vote down vote up
private void load(ClassLoader loader, String name) {
    try {
        DefaultListableBeanFactory lbf = (DefaultListableBeanFactory) applicationContext.getAutowireCapableBeanFactory();
        BeanDefinition bd = BeanDefinitionReaderUtils.createBeanDefinition(null, name, loader);
        String dynamicBeanName = generator.uuid();
        lbf.registerBeanDefinition(dynamicBeanName, bd);
        Object bean = lbf.getBean(dynamicBeanName);
        String beanName = getBeanName(bean.getClass());
        Object oldBean = null;
        if (beanName != null) {
            oldBean = container.getBean(beanName);
            container.mapBeanName(beanName, dynamicBeanName);
        }
        inject(bean.getClass(), null, bean);
        inject(bean, oldBean);
    } catch (Exception e) {
        logger.warn(e, "重新载入[{}]时发生异常!", name);
    }
}
 
Example 14
/**
 * Process the given bean element, parsing the bean definition
 * and registering it with the registry.
 */
protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
	BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
	if (bdHolder != null) {
		bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
		try {
			// Register the final decorated instance.
			BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());
		}
		catch (BeanDefinitionStoreException ex) {
			getReaderContext().error("Failed to register bean definition with name '" +
					bdHolder.getBeanName() + "'", ele, ex);
		}
		// Send registration event.
		getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));
	}
}
 
Example 15
@Test
public void naming() {
	String className = GeneratedNameBean.class.getName();

	String targetName = className + BeanDefinitionReaderUtils.GENERATED_BEAN_NAME_SEPARATOR + "0";
	GeneratedNameBean topLevel1 = (GeneratedNameBean) beanFactory.getBean(targetName);
	assertNotNull(topLevel1);

	targetName = className + BeanDefinitionReaderUtils.GENERATED_BEAN_NAME_SEPARATOR + "1";
	GeneratedNameBean topLevel2 = (GeneratedNameBean) beanFactory.getBean(targetName);
	assertNotNull(topLevel2);

	GeneratedNameBean child1 = topLevel1.getChild();
	assertNotNull(child1.getBeanName());
	assertTrue(child1.getBeanName().startsWith(className));

	GeneratedNameBean child2 = topLevel2.getChild();
	assertNotNull(child2.getBeanName());
	assertTrue(child2.getBeanName().startsWith(className));

	assertFalse(child1.getBeanName().equals(child2.getBeanName()));
}
 
Example 16
Source Project: hasor   Source File: AbstractHasorDefinitionParser.java    License: Apache License 2.0 6 votes vote down vote up
/**摘抄 Spring 源码,将Bean注册到容器中*/
private BeanDefinition registerBean(Element element, ParserContext parserContext, NamedNodeMap attributes, AbstractBeanDefinition definition) {
    if (!parserContext.isNested()) {
        try {
            String id = beanID(element, attributes);
            if (!StringUtils.hasText(id)) {
                parserContext.getReaderContext().error(beanID(element, attributes) + " is undefined. for element '" + element.getLocalName(), element);
            }
            BeanDefinitionHolder holder = new BeanDefinitionHolder(definition, id);
            BeanDefinitionReaderUtils.registerBeanDefinition(holder, parserContext.getRegistry());
            parserContext.registerComponent(new BeanComponentDefinition(holder));
        } catch (BeanDefinitionStoreException ex) {
            parserContext.getReaderContext().error(ex.getMessage(), element);
            return null;
        }
    }
    return definition;
}
 
Example 17
private void registerRetrofitClient(BeanDefinitionRegistry registry,
								 AnnotationMetadata annotationMetadata, Map<String, Object> attributes) {
	String className = annotationMetadata.getClassName();
	BeanDefinitionBuilder definition = BeanDefinitionBuilder
			.genericBeanDefinition(getFactoryBeanClass());
	validate(attributes);
	definition.addPropertyValue("url", getUrl(attributes));
	String name = getName(attributes);
	definition.addPropertyValue("name", name);
	definition.addPropertyValue("type", className);
	definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);

	String alias = name + "RetrofitClient";
	AbstractBeanDefinition beanDefinition = definition.getBeanDefinition();
	beanDefinition.setPrimary(true);

	String qualifier = getQualifier(attributes);
	if (StringUtils.hasText(qualifier)) {
		alias = qualifier;
	}

	BeanDefinitionHolder holder = new BeanDefinitionHolder(beanDefinition, className,
			new String[] { alias });
	BeanDefinitionReaderUtils.registerBeanDefinition(holder, registry);
}
 
Example 18
public static BeanDefinitionHolder registerAmazonWebserviceClient(Object source,
		BeanDefinitionRegistry registry, String serviceNameClassName,
		String customRegionProvider, String customRegion) {

	String beanName = getBeanName(serviceNameClassName);

	if (registry.containsBeanDefinition(beanName)) {
		return new BeanDefinitionHolder(registry.getBeanDefinition(beanName),
				beanName);
	}

	BeanDefinition definition = getAmazonWebserviceClientBeanDefinition(source,
			serviceNameClassName, customRegionProvider, customRegion, registry);
	BeanDefinitionHolder holder = new BeanDefinitionHolder(definition, beanName);
	BeanDefinitionReaderUtils.registerBeanDefinition(holder, registry);

	return holder;
}
 
Example 19
Source Project: dubbo-2.6.5   Source File: DubboComponentScanRegistrar.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Registers {@link ServiceAnnotationBeanPostProcessor}
 *
 * @param packagesToScan packages to scan without resolving placeholders
 * @param registry       {@link BeanDefinitionRegistry}
 * @since 2.5.8
 */
private void registerServiceAnnotationBeanPostProcessor(Set<String> packagesToScan, BeanDefinitionRegistry registry) {

    BeanDefinitionBuilder builder = rootBeanDefinition(ServiceAnnotationBeanPostProcessor.class);
    builder.addConstructorArgValue(packagesToScan);
    builder.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
    AbstractBeanDefinition beanDefinition = builder.getBeanDefinition();
    BeanDefinitionReaderUtils.registerWithGeneratedName(beanDefinition, registry);

}
 
Example 20
/**
 * Register a bean from the given bean class, deriving its metadata from
 * class-declared annotations.
 * @param annotatedClass the class of the bean
 * @param name an explicit name for the bean
 * @param supplier a callback for creating an instance of the bean
 * (may be {@code null})
 * @param qualifiers specific qualifier annotations to consider, if any,
 * in addition to qualifiers at the bean class level
 * @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> annotatedClass, @Nullable String name,
		@Nullable Class<? extends Annotation>[] qualifiers, @Nullable Supplier<T> supplier,
		@Nullable BeanDefinitionCustomizer[] customizers) {

	AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(annotatedClass);
	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);
}
 
Example 21
@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 22
public static void registerUserBeanDefinition(BeanDefinitionRegistry registry, String beanName) {
    BeanDefinitionBuilder beanDefinitionBuilder = genericBeanDefinition(User.class);
    beanDefinitionBuilder
            .addPropertyValue("id", 1L)
            .addPropertyValue("name", "小马哥");

    // 判断如果 beanName 参数存在时
    if (StringUtils.hasText(beanName)) {
        // 注册 BeanDefinition
        registry.registerBeanDefinition(beanName, beanDefinitionBuilder.getBeanDefinition());
    } else {
        // 非命名 Bean 注册方法
        BeanDefinitionReaderUtils.registerWithGeneratedName(beanDefinitionBuilder.getBeanDefinition(), registry);
    }
}
 
Example 23
/**
 * Register a bean from the given bean class, deriving its metadata from
 * class-declared annotations.
 * @param annotatedClass the class of the bean
 * @param instanceSupplier a callback for creating an instance of the bean
 * (may be {@code null})
 * @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 definitionCustomizers one or more callbacks for customizing the
 * factory's {@link BeanDefinition}, e.g. setting a lazy-init or primary flag
 * @since 5.0
 */
<T> void doRegisterBean(Class<T> annotatedClass, @Nullable Supplier<T> instanceSupplier, @Nullable String name,
		@Nullable Class<? extends Annotation>[] qualifiers, BeanDefinitionCustomizer... definitionCustomizers) {

	AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(annotatedClass);
	if (this.conditionEvaluator.shouldSkip(abd.getMetadata())) {
		return;
	}

	abd.setInstanceSupplier(instanceSupplier);
	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));
			}
		}
	}
	for (BeanDefinitionCustomizer customizer : definitionCustomizers) {
		customizer.customize(abd);
	}

	BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName);
	definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
	BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry);
}
 
Example 24
private void registerFeignClient(BeanDefinitionRegistry registry,
		AnnotationMetadata annotationMetadata, Map<String, Object> attributes) {
	String className = annotationMetadata.getClassName();
	BeanDefinitionBuilder definition = BeanDefinitionBuilder
			.genericBeanDefinition(FeignClientFactoryBean.class);
	validate(attributes);
	definition.addPropertyValue("url", getUrl(attributes));
	definition.addPropertyValue("path", getPath(attributes));
	String name = getName(attributes);
	definition.addPropertyValue("name", name);
	String contextId = getContextId(attributes);
	definition.addPropertyValue("contextId", contextId);
	definition.addPropertyValue("type", className);
	definition.addPropertyValue("decode404", attributes.get("decode404"));
	definition.addPropertyValue("fallback", attributes.get("fallback"));
	definition.addPropertyValue("fallbackFactory", attributes.get("fallbackFactory"));
	definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);

	String alias = contextId + "FeignClient";
	AbstractBeanDefinition beanDefinition = definition.getBeanDefinition();
	beanDefinition.setAttribute(FactoryBean.OBJECT_TYPE_ATTRIBUTE, className);

	// has a default, won't be null
	boolean primary = (Boolean) attributes.get("primary");

	beanDefinition.setPrimary(primary);

	String qualifier = getQualifier(attributes);
	if (StringUtils.hasText(qualifier)) {
		alias = qualifier;
	}

	BeanDefinitionHolder holder = new BeanDefinitionHolder(beanDefinition, className,
			new String[] { alias });
	BeanDefinitionReaderUtils.registerBeanDefinition(holder, registry);
}
 
Example 25
Source Project: spring-fu   Source File: AbstractCodecInitializer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void initialize(GenericApplicationContext context) {
	if (isClientCodec) {
		context.registerBean(BeanDefinitionReaderUtils.uniqueBeanName(WebClientCodecCustomizer.class.getName(), context), WebClientCodecCustomizer.class, () -> new WebClientCodecCustomizer(Arrays.asList((CodecCustomizer) configurer -> register(context, configurer))));
	}
	else {
		context.registerBean(BeanDefinitionReaderUtils.uniqueBeanName(CodecCustomizer.class.getName(), context), CodecCustomizer.class, () -> configurer -> register(context, configurer));
	}
}
 
Example 26
Source Project: spring-fu   Source File: WebMvcServerDsl.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Configure routes via {@link RouterFunctions.Builder}.
 * @see org.springframework.fu.jafu.BeanDefinitionDsl#bean(Class, BeanDefinitionCustomizer...)
 */
public WebMvcServerDsl router(Consumer<RouterFunctions.Builder> routerDsl) {
	RouterFunctions.Builder builder = RouterFunctions.route();
	context.registerBean(BeanDefinitionReaderUtils.uniqueBeanName(RouterFunction.class.getName(), context), RouterFunction.class, () -> {
		routerDsl.accept(builder);
		return builder.build();
	});
	return this;
}
 
Example 27
Source Project: spring-fu   Source File: WebFluxServerDsl.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Configure routes via {@link RouterFunctions.Builder}.
 * @see org.springframework.fu.jafu.BeanDefinitionDsl#bean(Class, BeanDefinitionCustomizer...)
 */
public WebFluxServerDsl router(Consumer<RouterFunctions.Builder> routerDsl) {
	RouterFunctions.Builder builder = RouterFunctions.route();
	context.registerBean(BeanDefinitionReaderUtils.uniqueBeanName(RouterFunction.class.getName(), context), RouterFunction.class, () -> {
		routerDsl.accept(builder);
		return builder.build();
	});
	return this;
}
 
Example 28
Source Project: BootNettyRpc   Source File: NettyRpcRegistrar.java    License: Apache License 2.0 5 votes vote down vote up
private void registerRpcClient(BeanDefinitionRegistry registry, AnnotationMetadata annotationMetadata, Map<String, Object> attributes) {
    String className = annotationMetadata.getClassName();
    BeanDefinitionBuilder definition = BeanDefinitionBuilder
            .genericBeanDefinition( RpcClientEntity.class );
    definition.addPropertyValue( "name", attributes.get( "name" ) );
    definition.addPropertyValue( "isSyn", attributes.get( "isSyn" ) );
    definition.addPropertyValue( "host", attributes.get( "host" ) );
    definition.addPropertyValue( "port", attributes.get( "port" ) );
    definition.addPropertyValue( "rpcClz", attributes.get( "rpcClz" ) );
    definition.addPropertyValue( "traceIdIndex", attributes.get( "traceIdIndex" ) );
    definition.setAutowireMode( AbstractBeanDefinition.AUTOWIRE_BY_NAME );

    try {
        definition.addPropertyValue( "interfaze", Class.forName( className ) );
    } catch (ClassNotFoundException e) {
        LOG.error( "Get interface for name error", e );
    }
    // definition.setAutowireMode( AbstractBeanDefinition.AUTOWIRE_BY_TYPE );
    String alias = className;
    AbstractBeanDefinition beanDefinition = definition.getBeanDefinition();
    beanDefinition.setPrimary( false );
    definition.addPropertyValue( "interceptor", getInterceptor( beanDefinition.getPropertyValues() ) );

    BeanDefinitionHolder holder = new BeanDefinitionHolder( beanDefinition, className,
            new String[]{alias} );
    LOG.info( "registerRpcClient:" + className );
    BeanDefinitionReaderUtils.registerBeanDefinition( holder, registry );

}
 
Example 29
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
    // 复用 {@link ServerImportSelector} 实现,避免重复劳动
    ImportSelector importSelector = new ServerImportSelector();
    // 筛选 Class 名称集合
    String[] selectedClassNames = importSelector.selectImports(importingClassMetadata);
    // 创建 Bean 定义
    Stream.of(selectedClassNames)
            .map(BeanDefinitionBuilder::genericBeanDefinition) // 转化为 BeanDefinitionBuilder 对象
            .map(BeanDefinitionBuilder::getBeanDefinition)     // 转化为 BeanDefinition
            .forEach(beanDefinition ->
                    // 注册 BeanDefinition 到 BeanDefinitionRegistry
                    BeanDefinitionReaderUtils.registerWithGeneratedName(beanDefinition, registry)
            );
}
 
Example 30
/**
 * Register a bean from the given bean class, deriving its metadata from
 * class-declared annotations.
 * @param annotatedClass the class of the bean
 * @param name an explicit name for the bean
 * @param qualifiers specific qualifier annotations to consider,
 * in addition to qualifiers at the bean class level
 */
@SuppressWarnings("unchecked")
public void registerBean(Class<?> annotatedClass, String name, Class<? extends Annotation>... qualifiers) {
	AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(annotatedClass);
	if (this.conditionEvaluator.shouldSkip(abd.getMetadata())) {
		return;
	}

	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));
			}
		}
	}

	BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName);
	definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
	BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry);
}