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

The following examples show how to use org.springframework.beans.factory.support.AbstractBeanDefinition. 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
@Override
protected AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) {
  final BeanDefinitionBuilder beanDefBuilder = BeanDefinitionBuilder.rootBeanDefinition(CuratorFrameworkFactoryBean.class);
  beanDefBuilder.setRole(ROLE_APPLICATION);
  beanDefBuilder.getRawBeanDefinition().setSource(parserContext.extractSource(element));
  
  beanDefBuilder.addPropertyValue("connectString", element.getAttribute("connect-string"));
  
  Element retryPolicyElement = DomUtils.getChildElementByTagName(element, "retry-policy");
  if (retryPolicyElement != null) {
    Element retryPolicyBeanElement = DomUtils.getChildElements(retryPolicyElement).get(0);
    BeanDefinitionHolder retryPolicy = parserContext.getDelegate().parseBeanDefinitionElement(retryPolicyBeanElement, beanDefBuilder.getBeanDefinition());
    beanDefBuilder.addPropertyValue("retryPolicy", retryPolicy);
  }

  Node namespace = element.getAttributeNode("namespace");
  if (namespace != null) {
    beanDefBuilder.addPropertyValue("namespace", namespace.getNodeValue());
  }

  return beanDefBuilder.getBeanDefinition();
}
 
Example 2
Source Project: spring-analysis-note   Source File: ConfigBeanDefinitionParser.java    License: MIT License 6 votes vote down vote up
/**
 * Create a {@link RootBeanDefinition} for the advisor described in the supplied. Does <strong>not</strong>
 * parse any associated '{@code pointcut}' or '{@code pointcut-ref}' attributes.
 */
private AbstractBeanDefinition createAdvisorBeanDefinition(Element advisorElement, ParserContext parserContext) {
	RootBeanDefinition advisorDefinition = new RootBeanDefinition(DefaultBeanFactoryPointcutAdvisor.class);
	advisorDefinition.setSource(parserContext.extractSource(advisorElement));

	String adviceRef = advisorElement.getAttribute(ADVICE_REF);
	if (!StringUtils.hasText(adviceRef)) {
		parserContext.getReaderContext().error(
				"'advice-ref' attribute contains empty value.", advisorElement, this.parseState.snapshot());
	}
	else {
		advisorDefinition.getPropertyValues().add(
				ADVICE_BEAN_NAME, new RuntimeBeanNameReference(adviceRef));
	}

	if (advisorElement.hasAttribute(ORDER_PROPERTY)) {
		advisorDefinition.getPropertyValues().add(
				ORDER_PROPERTY, advisorElement.getAttribute(ORDER_PROPERTY));
	}

	return advisorDefinition;
}
 
Example 3
Source Project: redisson   Source File: RedissonDefinitionParser.java    License: Apache License 2.0 6 votes vote down vote up
private void parseConfigTypes(Element element, String configType, BeanDefinitionBuilder redissonDef, ParserContext parserContext) {
    BeanDefinitionBuilder builder
            = helper.createBeanDefinitionBuilder(element,
                    parserContext, null);
    //Use factory method on the Config bean
    AbstractBeanDefinition bd = builder.getRawBeanDefinition();
    bd.setFactoryMethodName("use" + StringUtils.capitalize(configType));
    bd.setFactoryBeanName(parserContext.getContainingComponent().getName());
    String id = parserContext.getReaderContext().generateBeanName(bd);
    helper.registerBeanDefinition(builder, id,
            helper.parseAliase(element), parserContext);
    helper.parseAttributes(element, parserContext, builder);
    redissonDef.addDependsOn(id);
    parseChildElements(element, id, null, redissonDef, parserContext);
    parserContext.getDelegate().parseQualifierElements(element, bd);
}
 
Example 4
@Override
protected AbstractBeanDefinition parseInternal(final Element element, final ParserContext parserContext) {
    String type = element.getLocalName();
    switch (type) {
        case ShardingStrategyBeanDefinitionTag.STANDARD_STRATEGY_ROOT_TAG:
            return getStandardShardingStrategyConfigBeanDefinition(element);
        case ShardingStrategyBeanDefinitionTag.COMPLEX_STRATEGY_ROOT_TAG:
            return getComplexShardingStrategyConfigBeanDefinition(element);
        case ShardingStrategyBeanDefinitionTag.HINT_STRATEGY_ROOT_TAG:
            return getHintShardingStrategyConfigBeanDefinition(element);
        case ShardingStrategyBeanDefinitionTag.NONE_STRATEGY_ROOT_TAG:
            return getNoneShardingStrategyConfigBeanDefinition();
        default:
            throw new ShardingSphereException("Cannot support type: %s", type);
    }
}
 
Example 5
Source Project: joyqueue   Source File: AccessPointBeanDefinitionParser.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public BeanDefinition parse(Element element, ParserContext parserContext) {
    String id = element.getAttribute(ATTRIBUTE_ID);
    String url = element.getAttribute(ATTRIBUTE_URL);

    Assert.hasText(url, String.format("%s can not be blank", ATTRIBUTE_URL));

    if (!StringUtils.hasText(id)) {
        id = OMSSpringConsts.DEFAULT_ACCESS_POINT_ID;
    }

    BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.rootBeanDefinition(AccessPointContainer.class)
            .addConstructorArgValue(id)
            .addConstructorArgValue(url);
    List<BeanDefinition> attributes = parseAttributes(beanDefinitionBuilder, element, parserContext);
    beanDefinitionBuilder.addConstructorArgValue(attributes);

    AbstractBeanDefinition beanDefinition = beanDefinitionBuilder.getBeanDefinition();
    parserContext.getRegistry().registerBeanDefinition(id, beanDefinition);
    return beanDefinition;
}
 
Example 6
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);
}
 
Example 7
Source Project: blog_demos   Source File: BeanDefinitionParserDelegate.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
public int getAutowireMode(String attValue) {
	String att = attValue;
	if (DEFAULT_VALUE.equals(att)) {
		att = this.defaults.getAutowire();
	}
	int autowire = AbstractBeanDefinition.AUTOWIRE_NO;
	if (AUTOWIRE_BY_NAME_VALUE.equals(att)) {
		autowire = AbstractBeanDefinition.AUTOWIRE_BY_NAME;
	}
	else if (AUTOWIRE_BY_TYPE_VALUE.equals(att)) {
		autowire = AbstractBeanDefinition.AUTOWIRE_BY_TYPE;
	}
	else if (AUTOWIRE_CONSTRUCTOR_VALUE.equals(att)) {
		autowire = AbstractBeanDefinition.AUTOWIRE_CONSTRUCTOR;
	}
	else if (AUTOWIRE_AUTODETECT_VALUE.equals(att)) {
		autowire = AbstractBeanDefinition.AUTOWIRE_AUTODETECT;
	}
	// Else leave default value.
	return autowire;
}
 
Example 8
protected AbstractBeanDefinition createBeanDefinition() {
	AbstractBeanDefinition bd = new GenericBeanDefinition();
	bd.setBeanClass(this.clazz);
	if (!CollectionUtils.isEmpty(this.constructorArgs)) {
		ConstructorArgumentValues cav = new ConstructorArgumentValues();
		for (Object constructorArg : this.constructorArgs) {
			cav.addGenericArgumentValue(constructorArg);
		}
		bd.setConstructorArgumentValues(cav);
	}
	if (this.parentName != null) {
		bd.setParentName(this.parentName);
	}
	this.definitionWrapper = new BeanWrapperImpl(bd);
	return bd;
}
 
Example 9
@SuppressWarnings("deprecation")
public int getAutowireMode(String attValue) {
	String att = attValue;
	if (isDefaultValue(att)) {
		att = this.defaults.getAutowire();
	}
	int autowire = AbstractBeanDefinition.AUTOWIRE_NO;
	if (AUTOWIRE_BY_NAME_VALUE.equals(att)) {
		autowire = AbstractBeanDefinition.AUTOWIRE_BY_NAME;
	}
	else if (AUTOWIRE_BY_TYPE_VALUE.equals(att)) {
		autowire = AbstractBeanDefinition.AUTOWIRE_BY_TYPE;
	}
	else if (AUTOWIRE_CONSTRUCTOR_VALUE.equals(att)) {
		autowire = AbstractBeanDefinition.AUTOWIRE_CONSTRUCTOR;
	}
	else if (AUTOWIRE_AUTODETECT_VALUE.equals(att)) {
		autowire = AbstractBeanDefinition.AUTOWIRE_AUTODETECT;
	}
	// Else leave default value.
	return autowire;
}
 
Example 10
Source Project: onetwo   Source File: AbstractApiClentRegistrar.java    License: Apache License 2.0 6 votes vote down vote up
/***
	 * @see RestApiClientConfiguration#apiClientRestExecutor()
	 * @author wayshall
	 * @param annotationMetadataHelper
	 * @param registry
	 */
	@Deprecated
	protected void regiseterRestExecutor(AnnotationMetadataHelper annotationMetadataHelper, BeanDefinitionRegistry registry){
		if(registry.containsBeanDefinition(RestExecutorFactory.REST_EXECUTOR_FACTORY_BEAN_NAME)){
			return ;
		}
		Class<?> restExecutorFacotryClass = (Class<?>)annotationMetadataHelper.getAttributes().get(ATTRS_REST_EXECUTOR_FACTORY);
//		RestExecutorFactory factory = null;
		if(restExecutorFacotryClass==null || restExecutorFacotryClass==RestExecutorFactory.class){
			restExecutorFacotryClass = DefaultRestExecutorFactory.class;
		}
		BeanDefinitionBuilder definition = BeanDefinitionBuilder.genericBeanDefinition(restExecutorFacotryClass);
		definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);
		registry.registerBeanDefinition(RestExecutorFactory.REST_EXECUTOR_FACTORY_BEAN_NAME, definition.getBeanDefinition());
		
	}
 
Example 11
Source Project: spring-batch-lightmin   Source File: BeanRegistrar.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * registers beans within the current application context of the given class with the given parameters
 *
 * @param beanClass             Class of the bean to be generated
 * @param beanName              unique name of the bean to be generated
 * @param constructorValues     Set of Objects, which will be passed as contructor values
 * @param constructorReferences Set of Object which will be passed as constructor references
 * @param propertyValues        Map of String,Object which will be passed to the key (property) name as value
 * @param propertyReferences    Map of String,Object which will be passed to the key (property) name as reference
 * @param dependsOnBeans        Set of Strings, which contains depending bean names
 */
public void registerBean(final Class<?> beanClass, final String beanName,
                         final Set<Object> constructorValues,
                         final Set<String> constructorReferences,
                         final Map<String, Object> propertyValues,
                         final Map<String, String> propertyReferences,
                         final Set<String> dependsOnBeans) {
    final BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(beanClass);
    builder.setAutowireMode(AbstractBeanDefinition.DEPENDENCY_CHECK_ALL);
    addConstructorArgReferences(builder, constructorReferences);
    addConstructorArgValues(builder, constructorValues);
    addPropertyReference(builder, propertyReferences);
    addPropertyValues(builder, propertyValues);
    addDependsOnBean(builder, dependsOnBeans);
    final DefaultListableBeanFactory factory = (DefaultListableBeanFactory) context.getBeanFactory();
    factory.registerBeanDefinition(beanName, builder.getBeanDefinition());
}
 
Example 12
Source Project: syncope   Source File: AuthDataAccessor.java    License: Apache License 2.0 6 votes vote down vote up
public JWTSSOProvider getJWTSSOProvider(final String issuer) {
    synchronized (this) {
        if (jwtSSOProviders == null) {
            jwtSSOProviders = new HashMap<>();

            implementationLookup.getJWTSSOProviderClasses().stream().
                    map(clazz -> (JWTSSOProvider) ApplicationContextProvider.getBeanFactory().
                    createBean(clazz, AbstractBeanDefinition.AUTOWIRE_BY_TYPE, true)).
                    forEach(jwtSSOProvider -> jwtSSOProviders.put(jwtSSOProvider.getIssuer(), jwtSSOProvider));
        }
    }

    if (issuer == null) {
        throw new AuthenticationCredentialsNotFoundException("A null issuer is not permitted");
    }
    JWTSSOProvider provider = jwtSSOProviders.get(issuer);
    if (provider == null) {
        throw new AuthenticationCredentialsNotFoundException(
                "Could not find any registered JWTSSOProvider for issuer " + issuer);
    }

    return provider;
}
 
Example 13
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry)
                                                                              throws BeansException {
    BeanDefinitionBuilder definitionBuilder = BeanDefinitionBuilder
        .genericBeanDefinition(HikariDataSource.class);
    AbstractBeanDefinition beanDefinition = definitionBuilder.getRawBeanDefinition();
    beanDefinition.setDestroyMethodName("close");
    beanDefinition.setPrimary(false);

    definitionBuilder.addPropertyValue("driverClassName", "org.h2.Driver");
    definitionBuilder
        .addPropertyValue(
            "jdbcUrl",
            "jdbc:mysql://1.1.1.1:3306/xxx?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull");
    definitionBuilder.addPropertyValue("username", "sofa");
    definitionBuilder.addPropertyValue("password", "123456");

    registry.registerBeanDefinition("manualDataSource",
        definitionBuilder.getRawBeanDefinition());
}
 
Example 14
/**
 * Resolves class of a beanDefinition
 * @param beanDefinition the bean definition
 * @return class of the bean definition
 * @throws IllegalStateException if the given bean definition class can not
 * be resolved
 * @see org.springframework.beans.factory.config.BeanDefinition#setBeanClassName(String)
 * @see org.springframework.beans.factory.support.AbstractBeanDefinition#resolveBeanClass(ClassLoader)
 */
protected Class resolveBeanClass(BeanDefinition beanDefinition)
		throws IllegalStateException {
	try {
		return ((AbstractBeanDefinition) beanDefinition)
				.resolveBeanClass(ClassUtils.getDefaultClassLoader());
	} catch (ClassNotFoundException e) {
		throw new IllegalStateException("Could not resolve class ["
				+ beanDefinition.getBeanClassName() + "] of caching listener");
	}
}
 
Example 15
/**
 * Parses the supplied {@code <advisor>} element and registers the resulting
 * {@link org.springframework.aop.Advisor} and any resulting {@link org.springframework.aop.Pointcut}
 * with the supplied {@link BeanDefinitionRegistry}.
 */
private void parseAdvisor(Element advisorElement, ParserContext parserContext) {
	AbstractBeanDefinition advisorDef = createAdvisorBeanDefinition(advisorElement, parserContext);
	String id = advisorElement.getAttribute(ID);

	try {
		this.parseState.push(new AdvisorEntry(id));
		String advisorBeanName = id;
		if (StringUtils.hasText(advisorBeanName)) {
			parserContext.getRegistry().registerBeanDefinition(advisorBeanName, advisorDef);
		}
		else {
			advisorBeanName = parserContext.getReaderContext().registerWithGeneratedName(advisorDef);
		}

		Object pointcut = parsePointcutProperty(advisorElement, parserContext);
		if (pointcut instanceof BeanDefinition) {
			advisorDef.getPropertyValues().add(POINTCUT, pointcut);
			parserContext.registerComponent(
					new AdvisorComponentDefinition(advisorBeanName, advisorDef, (BeanDefinition) pointcut));
		}
		else if (pointcut instanceof String) {
			advisorDef.getPropertyValues().add(POINTCUT, new RuntimeBeanReference((String) pointcut));
			parserContext.registerComponent(
					new AdvisorComponentDefinition(advisorBeanName, advisorDef));
		}
	}
	finally {
		this.parseState.pop();
	}
}
 
Example 16
@Override
//CHECKSTYLE:OFF
protected AbstractBeanDefinition parseInternal(final Element element, final ParserContext parserContext) {
//CHECKSTYLE:ON
    BeanDefinitionBuilder factory = BeanDefinitionBuilder.rootBeanDefinition(SpringShardingDataSource.class);//初始化调用SpringShardingDataSource
    //有参构造参数,但是参数默认是null
    factory.addConstructorArgValue(parseShardingRuleConfig(element, parserContext));//设置构造参数的值
    //解析props节点,这个节点值是对sharding-jdbc的一些属性解析,比如允许不允许打印sharding-jdbc的日志
    factory.addConstructorArgValue(parseProperties(element, parserContext));
    factory.setDestroyMethodName("close");
    return factory.getBeanDefinition();
}
 
Example 17
/**
 * Creates a {@link BeanDefinitionBuilder} instance for the
 * {@link #getBeanClass bean Class} and passes it to the
 * {@link #doParse} strategy method.
 * @param element the element that is to be parsed into a single BeanDefinition
 * @param parserContext the object encapsulating the current state of the parsing process
 * @return the BeanDefinition resulting from the parsing of the supplied {@link Element}
 * @throws IllegalStateException if the bean {@link Class} returned from
 * {@link #getBeanClass(org.w3c.dom.Element)} is {@code null}
 * @see #doParse
 */
@Override
protected final AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) {
	BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition();
	String parentName = getParentName(element);
	if (parentName != null) {
		builder.getRawBeanDefinition().setParentName(parentName);
	}
	Class<?> beanClass = getBeanClass(element);
	if (beanClass != null) {
		builder.getRawBeanDefinition().setBeanClass(beanClass);
	}
	else {
		String beanClassName = getBeanClassName(element);
		if (beanClassName != null) {
			builder.getRawBeanDefinition().setBeanClassName(beanClassName);
		}
	}
	builder.getRawBeanDefinition().setSource(parserContext.extractSource(element));
	if (parserContext.isNested()) {
		// Inner bean definition must receive same scope as containing bean.
		builder.setScope(parserContext.getContainingBeanDefinition().getScope());
	}
	if (parserContext.isDefaultLazyInit()) {
		// Default-lazy-init applies to custom bean definitions as well.
		builder.setLazyInit(true);
	}
	doParse(element, parserContext, builder);
	return builder.getBeanDefinition();
}
 
Example 18
Source Project: zxl   Source File: MulCommonBaseServiceParser.java    License: Apache License 2.0 5 votes vote down vote up
private BeanDefinition buildHibernateTransactionManagerBeanDefinition(Element element, String name) {
	AbstractBeanDefinition beanDefinition = new GenericBeanDefinition();
	beanDefinition.setAttribute(ID_ATTRIBUTE, name + HIBERNATE_TRANSACTION_MANAGER_SUFFIX);
	beanDefinition.setBeanClass(HibernateTransactionManager.class);
	MutablePropertyValues propertyValues = new MutablePropertyValues();
	propertyValues.add("sessionFactory", new RuntimeBeanReference(name + SESSION_FACTORY_SUFFIX));
	beanDefinition.setPropertyValues(propertyValues);
	return beanDefinition;
}
 
Example 19
Source Project: lams   Source File: UtilNamespaceHandler.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
protected String resolveId(Element element, AbstractBeanDefinition definition, ParserContext parserContext) {
	String id = super.resolveId(element, definition, parserContext);
	if (!StringUtils.hasText(id)) {
		id = element.getAttribute("static-field");
	}
	return id;
}
 
Example 20
@Test(expected = IllegalStateException.class)
public void testScopingBeanToUnregisteredScopeResultsInAnException() {
	BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(TestBean.class);
	AbstractBeanDefinition beanDefinition = builder.getBeanDefinition();
	beanDefinition.setScope("he put himself so low could hardly look me in the face");

	DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
	factory.registerBeanDefinition("testBean", beanDefinition);
	factory.getBean("testBean");
}
 
Example 21
/**
 * Parses the supplied {@code <advisor>} element and registers the resulting
 * {@link org.springframework.aop.Advisor} and any resulting {@link org.springframework.aop.Pointcut}
 * with the supplied {@link BeanDefinitionRegistry}.
 */
private void parseAdvisor(Element advisorElement, ParserContext parserContext) {
	AbstractBeanDefinition advisorDef = createAdvisorBeanDefinition(advisorElement, parserContext);
	String id = advisorElement.getAttribute(ID);

	try {
		this.parseState.push(new AdvisorEntry(id));
		String advisorBeanName = id;
		if (StringUtils.hasText(advisorBeanName)) {
			parserContext.getRegistry().registerBeanDefinition(advisorBeanName, advisorDef);
		}
		else {
			advisorBeanName = parserContext.getReaderContext().registerWithGeneratedName(advisorDef);
		}

		Object pointcut = parsePointcutProperty(advisorElement, parserContext);
		if (pointcut instanceof BeanDefinition) {
			advisorDef.getPropertyValues().add(POINTCUT, pointcut);
			parserContext.registerComponent(
					new AdvisorComponentDefinition(advisorBeanName, advisorDef, (BeanDefinition) pointcut));
		}
		else if (pointcut instanceof String) {
			advisorDef.getPropertyValues().add(POINTCUT, new RuntimeBeanReference((String) pointcut));
			parserContext.registerComponent(
					new AdvisorComponentDefinition(advisorBeanName, advisorDef));
		}
	}
	finally {
		this.parseState.pop();
	}
}
 
Example 22
/**
 * 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;
}
 
Example 23
@Test
public void testGetAttributes() {

    Bean annotation = getAnnotation("dummyBean", Bean.class);

    Map<String, Object> attributes = getAttributes(annotation, true);
    Assert.assertTrue(Arrays.equals(new String[]{"dummy-bean"}, (String[]) attributes.get("name")));

    attributes = getAttributes(annotation, true);
    Assert.assertTrue(Arrays.equals(new String[]{"dummy-bean"}, (String[]) attributes.get("name")));

    attributes = getAttributes(annotation, false);
    assertEquals(Autowire.NO, attributes.get("autowire"));
    assertEquals("", attributes.get("initMethod"));
    assertEquals(AbstractBeanDefinition.INFER_METHOD, attributes.get("destroyMethod"));

    MockEnvironment environment = new MockEnvironment();

    attributes = getAttributes(annotation, environment, false);
    assertEquals(Autowire.NO, attributes.get("autowire"));
    assertEquals("", attributes.get("initMethod"));
    assertEquals(AbstractBeanDefinition.INFER_METHOD, attributes.get("destroyMethod"));

    annotation = getAnnotation("dummyBean2", Bean.class);

    attributes = getAttributes(annotation, true);
    Assert.assertTrue(attributes.isEmpty());

    attributes = getAttributes(annotation, environment, true);
    Assert.assertTrue(attributes.isEmpty());

    environment.setProperty("beanName", "Your Bean Name");

    annotation = getAnnotation("dummyBean3", Bean.class);
    attributes = getAttributes(annotation, environment, true);
    Assert.assertTrue(Arrays.deepEquals(of(environment.getProperty("beanName")), (String[]) attributes.get("name")));

}
 
Example 24
/**
 * Resolve the ID for the supplied {@link BeanDefinition}.
 * <p>When using {@link #shouldGenerateId generation}, a name is generated automatically.
 * Otherwise, the ID is extracted from the "id" attribute, potentially with a
 * {@link #shouldGenerateIdAsFallback() fallback} to a generated id.
 * @param element the element that the bean definition has been built from
 * @param definition the bean definition to be registered
 * @param parserContext the object encapsulating the current state of the parsing process;
 * provides access to a {@link org.springframework.beans.factory.support.BeanDefinitionRegistry}
 * @return the resolved id
 * @throws BeanDefinitionStoreException if no unique name could be generated
 * for the given bean definition
 */
protected String resolveId(Element element, AbstractBeanDefinition definition, ParserContext parserContext)
		throws BeanDefinitionStoreException {

	if (shouldGenerateId()) {
		return parserContext.getReaderContext().generateBeanName(definition);
	}
	else {
		String id = element.getAttribute(ID_ATTRIBUTE);
		if (!StringUtils.hasText(id) && shouldGenerateIdAsFallback()) {
			id = parserContext.getReaderContext().generateBeanName(definition);
		}
		return id;
	}
}
 
Example 25
Source Project: hasor   Source File: HasorDefinitionParser.java    License: Apache License 2.0 5 votes vote down vote up
protected BeanDefinitionHolder createBeanHolder(String beanType, ParserContext parserContext, Consumer<BeanDefinitionBuilder> buildBean) {
    BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(beanType);
    builder.setAutowireMode(AutowireCapableBeanFactory.AUTOWIRE_AUTODETECT);
    buildBean.accept(builder);
    //
    AbstractBeanDefinition startWithDefine = builder.getBeanDefinition();
    String beanName = new DefaultBeanNameGenerator().generateBeanName(startWithDefine, parserContext.getRegistry());
    return new BeanDefinitionHolder(startWithDefine, beanName);
}
 
Example 26
/**
 * Parses the supplied {@code <pointcut>} and registers the resulting
 * Pointcut with the BeanDefinitionRegistry.
 */
private AbstractBeanDefinition parsePointcut(Element pointcutElement, ParserContext parserContext) {
	String id = pointcutElement.getAttribute(ID);
	String expression = pointcutElement.getAttribute(EXPRESSION);

	AbstractBeanDefinition pointcutDefinition = null;

	try {
		this.parseState.push(new PointcutEntry(id));
		pointcutDefinition = createPointcutDefinition(expression);
		pointcutDefinition.setSource(parserContext.extractSource(pointcutElement));

		String pointcutBeanName = id;
		if (StringUtils.hasText(pointcutBeanName)) {
			parserContext.getRegistry().registerBeanDefinition(pointcutBeanName, pointcutDefinition);
		}
		else {
			pointcutBeanName = parserContext.getReaderContext().registerWithGeneratedName(pointcutDefinition);
		}

		parserContext.registerComponent(
				new PointcutComponentDefinition(pointcutBeanName, pointcutDefinition, expression));
	}
	finally {
		this.parseState.pop();
	}

	return pointcutDefinition;
}
 
Example 27
Source Project: blog_demos   Source File: UtilNamespaceHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected String resolveId(Element element, AbstractBeanDefinition definition, ParserContext parserContext) {
	String id = super.resolveId(element, definition, parserContext);
	if (!StringUtils.hasText(id)) {
		id = element.getAttribute("path");
	}
	return id;
}
 
Example 28
@Override
protected AbstractBeanDefinition parseConsumer(Element element,
		ParserContext parserContext) {

	final BeanDefinitionBuilder snsOutboundChannelAdapterBuilder = BeanDefinitionBuilder
			.genericBeanDefinition(SnsOutboundGateway.class);
	final BeanDefinitionBuilder snsExecutorBuilder = SnsParserUtils
			.getSnsExecutorBuilder(element, parserContext);

	final BeanDefinition snsExecutorBuilderBeanDefinition = snsExecutorBuilder
			.getBeanDefinition();
	final String channelAdapterId = this.resolveId(element,
			snsOutboundChannelAdapterBuilder.getRawBeanDefinition(),
			parserContext);
	final String snsExecutorBeanName = channelAdapterId + ".snsExecutor";

	SnsParserUtils.registerSubscriptions(element, parserContext,
			snsExecutorBuilder, channelAdapterId);

	parserContext.registerBeanComponent(new BeanComponentDefinition(
			snsExecutorBuilderBeanDefinition, snsExecutorBeanName));

	snsOutboundChannelAdapterBuilder.addPropertyReference("snsExecutor",
			snsExecutorBeanName);

	SnsParserUtils.registerExecutorProxy(element, snsExecutorBeanName,
			parserContext);

	snsOutboundChannelAdapterBuilder.addPropertyValue("producesReply",
			Boolean.FALSE);

	AwsParserUtils.registerPermissions(element, snsExecutorBuilder,
			parserContext);

	return snsOutboundChannelAdapterBuilder.getBeanDefinition();

}
 
Example 29
Source Project: syncope   Source File: PriorityPropagationTaskExecutor.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates new instances of {@link PropagationTaskCallable} for usage with
 * {@link java.util.concurrent.CompletionService}.
 *
 * @param taskInfo to be executed
 * @param reporter to report propagation execution status
 * @param executor user that triggered the propagation execution
 * @return new {@link PropagationTaskCallable} instance for usage with
 * {@link java.util.concurrent.CompletionService}
 */
protected static PropagationTaskCallable newPropagationTaskCallable(
        final PropagationTaskInfo taskInfo, final PropagationReporter reporter, final String executor) {

    PropagationTaskCallable callable = (PropagationTaskCallable) ApplicationContextProvider.getBeanFactory().
            createBean(DefaultPropagationTaskCallable.class, AbstractBeanDefinition.AUTOWIRE_BY_TYPE, false);
    callable.setTaskInfo(taskInfo);
    callable.setReporter(reporter);
    callable.setExecutor(executor);

    return callable;
}
 
Example 30
@Override
protected AbstractBeanDefinition parseInternal(final Element element, final ParserContext parserContext) {
    BeanDefinitionBuilder factory = BeanDefinitionBuilder.rootBeanDefinition(beanClass);
    factory.addConstructorArgValue(element.getAttribute(ShardingSphereAlgorithmBeanDefinitionTag.TYPE_ATTRIBUTE));
    factory.addConstructorArgValue(parsePropsElement(element, parserContext));
    return factory.getBeanDefinition();
}