org.springframework.beans.factory.config.BeanDefinition Java Examples

The following examples show how to use org.springframework.beans.factory.config.BeanDefinition. 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 Project: java-technology-stack   Author: codeEngraver   File: LiveBeansView.java    License: MIT License 6 votes vote down vote up
/**
 * Determine a resource description for the given bean definition and
 * apply basic JSON escaping (backslashes, double quotes) to it.
 * @param bd the bean definition to build the resource description for
 * @return the JSON-escaped resource description
 */
@Nullable
protected String getEscapedResourceDescription(BeanDefinition bd) {
	String resourceDescription = bd.getResourceDescription();
	if (resourceDescription == null) {
		return null;
	}
	StringBuilder result = new StringBuilder(resourceDescription.length() + 16);
	for (int i = 0; i < resourceDescription.length(); i++) {
		char character = resourceDescription.charAt(i);
		if (character == '\\') {
			result.append('/');
		}
		else if (character == '"') {
			result.append("\\").append('"');
		}
		else {
			result.append(character);
		}
	}
	return result.toString();
}
 
Example #2
Source Project: lams   Author: lamsfoundation   File: BeanDefinitionParserDelegate.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Parse a property element.
 */
public void parsePropertyElement(Element ele, BeanDefinition bd) {
	String propertyName = ele.getAttribute(NAME_ATTRIBUTE);
	if (!StringUtils.hasLength(propertyName)) {
		error("Tag 'property' must have a 'name' attribute", ele);
		return;
	}
	this.parseState.push(new PropertyEntry(propertyName));
	try {
		if (bd.getPropertyValues().contains(propertyName)) {
			error("Multiple 'property' definitions for property '" + propertyName + "'", ele);
			return;
		}
		Object val = parsePropertyValue(ele, bd, propertyName);
		PropertyValue pv = new PropertyValue(propertyName, val);
		parseMetaElements(ele, pv);
		pv.setSource(extractSource(ele));
		bd.getPropertyValues().addPropertyValue(pv);
	}
	finally {
		this.parseState.pop();
	}
}
 
Example #3
Source Project: cloudbreak   Author: hortonworks   File: ValidIfExactlyOneNonNullCheckerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testAllAnnotatedClasses() throws NoSuchFieldException, ClassNotFoundException {
    ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
    scanner.addIncludeFilter(new AnnotationTypeFilter(ValidIfExactlyOneNonNull.class));
    for (BeanDefinition def : scanner.findCandidateComponents("com.sequenceiq.redbeams")) {
        String annotatedClassName = def.getBeanClassName();
        Class<?> annotatedClass = Class.forName(annotatedClassName);
        ValidIfExactlyOneNonNull classAnnotation = annotatedClass.getAnnotation(ValidIfExactlyOneNonNull.class);
        String[] fields = classAnnotation.fields();
        if (fields.length == 0) {
            fail("ValidIfExactlyOneNonNull annotation on class " + annotatedClassName + " has no fields");
        }
        for (String fieldName : classAnnotation.fields()) {
            annotatedClass.getDeclaredField(fieldName);
            // if this does not throw an exception, great
        }
    }
}
 
Example #4
Source Project: spring4-understanding   Author: langtianya   File: ScheduledAnnotationBeanPostProcessorTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void fixedRateTask() {
	BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class);
	BeanDefinition targetDefinition = new RootBeanDefinition(FixedRateTestBean.class);
	context.registerBeanDefinition("postProcessor", processorDefinition);
	context.registerBeanDefinition("target", targetDefinition);
	context.refresh();

	Object postProcessor = context.getBean("postProcessor");
	Object target = context.getBean("target");
	ScheduledTaskRegistrar registrar = (ScheduledTaskRegistrar)
			new DirectFieldAccessor(postProcessor).getPropertyValue("registrar");
	@SuppressWarnings("unchecked")
	List<IntervalTask> fixedRateTasks = (List<IntervalTask>)
			new DirectFieldAccessor(registrar).getPropertyValue("fixedRateTasks");
	assertEquals(1, fixedRateTasks.size());
	IntervalTask task = fixedRateTasks.get(0);
	ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task.getRunnable();
	Object targetObject = runnable.getTarget();
	Method targetMethod = runnable.getMethod();
	assertEquals(target, targetObject);
	assertEquals("fixedRate", targetMethod.getName());
	assertEquals(0L, task.getInitialDelay());
	assertEquals(3000L, task.getInterval());
}
 
Example #5
Source Project: java-technology-stack   Author: codeEngraver   File: AnnotationDrivenCacheBeanDefinitionParser.java    License: MIT License 6 votes vote down vote up
/**
 * Parses the '{@code <cache:annotation-driven>}' tag. Will
 * {@link AopNamespaceUtils#registerAutoProxyCreatorIfNecessary
 * register an AutoProxyCreator} with the container as necessary.
 */
@Override
@Nullable
public BeanDefinition parse(Element element, ParserContext parserContext) {
	String mode = element.getAttribute("mode");
	if ("aspectj".equals(mode)) {
		// mode="aspectj"
		registerCacheAspect(element, parserContext);
	}
	else {
		// mode="proxy"
		registerCacheAdvisor(element, parserContext);
	}

	return null;
}
 
Example #6
Source Project: jdal   Author: chelu   File: DefaultsBeanDefinitionParser.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Register default TablePanel Actions
 * @param element current element
 * @param parserContext parserContext
 * @return a new ComponentDefinition with default table action list.
 */
private ComponentDefinition registerDefaultTableActions(Element element, ParserContext parserContext) {
	ManagedList<Object> actions = new ManagedList<Object>(7);
	actions.add(createBeanDefinition(AddAction.class, parserContext));
	actions.add(createBeanDefinition(SelectAllAction.class, parserContext));
	actions.add(createBeanDefinition(DeselectAllAction.class, parserContext));
	actions.add(createBeanDefinition(RemoveAllAction.class, parserContext));
	actions.add(createBeanDefinition(HideShowFilterAction.class, parserContext));
	actions.add(createBeanDefinition(ApplyFilterAction.class, parserContext));
	actions.add(createBeanDefinition(ClearFilterAction.class, parserContext));
	
	BeanDefinitionBuilder bdb = BeanDefinitionBuilder.genericBeanDefinition(ListFactoryBean.class);
	bdb.getRawBeanDefinition().setSource(parserContext.extractSource(element));
	bdb.addPropertyValue("sourceList", actions);
	bdb.setScope(BeanDefinition.SCOPE_PROTOTYPE);
	BeanComponentDefinition bcd = new BeanComponentDefinition(bdb.getBeanDefinition(), 
			DEFAULT_TABLE_ACTIONS);
	registerBeanComponentDefinition(element, parserContext, bcd);
	return bcd;
}
 
Example #7
Source Project: lams   Author: lamsfoundation   File: BeanDefinitionParserDelegate.java    License: GNU General Public License v2.0 6 votes vote down vote up
public BeanDefinitionHolder decorateIfRequired(
		Node node, BeanDefinitionHolder originalDef, BeanDefinition containingBd) {

	String namespaceUri = getNamespaceURI(node);
	if (!isDefaultNamespace(namespaceUri)) {
		NamespaceHandler handler = this.readerContext.getNamespaceHandlerResolver().resolve(namespaceUri);
		if (handler != null) {
			return handler.decorate(node, originalDef, new ParserContext(this.readerContext, this, containingBd));
		}
		else if (namespaceUri != null && namespaceUri.startsWith("http://www.springframework.org/")) {
			error("Unable to locate Spring NamespaceHandler for XML schema namespace [" + namespaceUri + "]", node);
		}
		else {
			// A custom namespace, not to be handled by Spring - maybe "xml:...".
			if (logger.isDebugEnabled()) {
				logger.debug("No Spring NamespaceHandler found for XML schema namespace [" + namespaceUri + "]");
			}
		}
	}
	return originalDef;
}
 
Example #8
Source Project: spring-analysis-note   Author: Vip-Augus   File: RequiredAnnotationBeanPostProcessorTests.java    License: MIT License 6 votes vote down vote up
@Test
public void testWithRequiredPropertyOmitted() {
	try {
		DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
		BeanDefinition beanDef = BeanDefinitionBuilder
			.genericBeanDefinition(RequiredTestBean.class)
			.addPropertyValue("name", "Rob Harrop")
			.addPropertyValue("favouriteColour", "Blue")
			.addPropertyValue("jobTitle", "Grand Poobah")
			.getBeanDefinition();
		factory.registerBeanDefinition("testBean", beanDef);
		factory.addBeanPostProcessor(new RequiredAnnotationBeanPostProcessor());
		factory.preInstantiateSingletons();
		fail("Should have thrown BeanCreationException");
	}
	catch (BeanCreationException ex) {
		String message = ex.getCause().getMessage();
		assertTrue(message.contains("Property"));
		assertTrue(message.contains("age"));
		assertTrue(message.contains("testBean"));
	}
}
 
Example #9
Source Project: lams   Author: lamsfoundation   File: ResourcesBeanDefinitionParser.java    License: GNU General Public License v2.0 6 votes vote down vote up
private void registerUrlProvider(ParserContext parserContext, Object source) {
	if (!parserContext.getRegistry().containsBeanDefinition(RESOURCE_URL_PROVIDER)) {
		RootBeanDefinition urlProvider = new RootBeanDefinition(ResourceUrlProvider.class);
		urlProvider.setSource(source);
		urlProvider.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
		parserContext.getRegistry().registerBeanDefinition(RESOURCE_URL_PROVIDER, urlProvider);
		parserContext.registerComponent(new BeanComponentDefinition(urlProvider, RESOURCE_URL_PROVIDER));

		RootBeanDefinition interceptor = new RootBeanDefinition(ResourceUrlProviderExposingInterceptor.class);
		interceptor.setSource(source);
		interceptor.getConstructorArgumentValues().addIndexedArgumentValue(0, urlProvider);

		RootBeanDefinition mappedInterceptor = new RootBeanDefinition(MappedInterceptor.class);
		mappedInterceptor.setSource(source);
		mappedInterceptor.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
		mappedInterceptor.getConstructorArgumentValues().addIndexedArgumentValue(0, (Object) null);
		mappedInterceptor.getConstructorArgumentValues().addIndexedArgumentValue(1, interceptor);
		String mappedInterceptorName = parserContext.getReaderContext().registerWithGeneratedName(mappedInterceptor);
		parserContext.registerComponent(new BeanComponentDefinition(mappedInterceptor, mappedInterceptorName));
	}
}
 
Example #10
Source Project: spring4-understanding   Author: langtianya   File: InjectAnnotationBeanPostProcessorTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testObjectFactoryFieldInjectionIntoPrototypeBean() {
	DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
	bf.setAutowireCandidateResolver(new QualifierAnnotationAutowireCandidateResolver());
	AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
	bpp.setBeanFactory(bf);
	bf.addBeanPostProcessor(bpp);
	RootBeanDefinition annotatedBeanDefinition = new RootBeanDefinition(ObjectFactoryQualifierFieldInjectionBean.class);
	annotatedBeanDefinition.setScope(BeanDefinition.SCOPE_PROTOTYPE);
	bf.registerBeanDefinition("annotatedBean", annotatedBeanDefinition);
	RootBeanDefinition bd = new RootBeanDefinition(TestBean.class);
	bd.addQualifier(new AutowireCandidateQualifier(Qualifier.class, "testBean"));
	bf.registerBeanDefinition("testBean", bd);
	bf.registerBeanDefinition("testBean2", new RootBeanDefinition(TestBean.class));

	ObjectFactoryQualifierFieldInjectionBean bean = (ObjectFactoryQualifierFieldInjectionBean) bf.getBean("annotatedBean");
	assertSame(bf.getBean("testBean"), bean.getTestBean());
	ObjectFactoryQualifierFieldInjectionBean anotherBean = (ObjectFactoryQualifierFieldInjectionBean) bf.getBean("annotatedBean");
	assertNotSame(anotherBean, bean);
	assertSame(bf.getBean("testBean"), bean.getTestBean());
}
 
Example #11
/**
 * 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);
}
 
Example #12
/**
 * Convert from an internal Spring bean definition to a DTO.
 * 
 * @param beanDefinition The internal Spring bean definition.
 * @return Returns a DTO representation.
 */
public BeanDefinitionInfo toDto(BeanDefinition beanDefinition) {
	if (beanDefinition instanceof GenericBeanDefinition) {
		GenericBeanDefinitionInfo info = new GenericBeanDefinitionInfo();
		info.setClassName(beanDefinition.getBeanClassName());

		if (beanDefinition.getPropertyValues() != null) {
			Map<String, BeanMetadataElementInfo> propertyValues = new HashMap<String, BeanMetadataElementInfo>();
			for (PropertyValue value : beanDefinition.getPropertyValues().getPropertyValueList()) {
				Object obj = value.getValue();
				if (obj instanceof BeanMetadataElement) {
					propertyValues.put(value.getName(), toDto((BeanMetadataElement) obj));
				} else {
					throw new IllegalArgumentException("Type " + obj.getClass().getName()
							+ " is not a BeanMetadataElement for property: " + value.getName());
				}
			}
			info.setPropertyValues(propertyValues);
		}
		return info;
	} else {
		throw new IllegalArgumentException("Conversion to DTO of " + beanDefinition.getClass().getName()
				+ " not implemented");
	}
}
 
Example #13
Source Project: spring-analysis-note   Author: Vip-Augus   File: LiveBeansView.java    License: MIT License 6 votes vote down vote up
/**
 * Determine a resource description for the given bean definition and
 * apply basic JSON escaping (backslashes, double quotes) to it.
 * @param bd the bean definition to build the resource description for
 * @return the JSON-escaped resource description
 */
@Nullable
protected String getEscapedResourceDescription(BeanDefinition bd) {
	String resourceDescription = bd.getResourceDescription();
	if (resourceDescription == null) {
		return null;
	}
	StringBuilder result = new StringBuilder(resourceDescription.length() + 16);
	for (int i = 0; i < resourceDescription.length(); i++) {
		char character = resourceDescription.charAt(i);
		if (character == '\\') {
			result.append('/');
		}
		else if (character == '"') {
			result.append("\\").append('"');
		}
		else {
			result.append(character);
		}
	}
	return result.toString();
}
 
Example #14
Source Project: lams   Author: lamsfoundation   File: AbstractAutowireCapableBeanFactory.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public Object autowire(Class<?> beanClass, int autowireMode, boolean dependencyCheck) throws BeansException {
	// Use non-singleton bean definition, to avoid registering bean as dependent bean.
	final RootBeanDefinition bd = new RootBeanDefinition(beanClass, autowireMode, dependencyCheck);
	bd.setScope(BeanDefinition.SCOPE_PROTOTYPE);
	if (bd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR) {
		return autowireConstructor(beanClass.getName(), bd, null, null).getWrappedInstance();
	}
	else {
		Object bean;
		final BeanFactory parent = this;
		if (System.getSecurityManager() != null) {
			bean = AccessController.doPrivileged(new PrivilegedAction<Object>() {
				@Override
				public Object run() {
					return getInstantiationStrategy().instantiate(bd, null, parent);
				}
			}, getAccessControlContext());
		}
		else {
			bean = getInstantiationStrategy().instantiate(bd, null, parent);
		}
		populateBean(beanClass.getName(), bd, new BeanWrapperImpl(bean));
		return bean;
	}
}
 
Example #15
Source Project: lams   Author: lamsfoundation   File: ViewResolversBeanDefinitionParser.java    License: GNU General Public License v2.0 6 votes vote down vote up
private BeanDefinition createContentNegotiatingViewResolver(Element resolverElement, ParserContext context) {
	RootBeanDefinition beanDef = new RootBeanDefinition(ContentNegotiatingViewResolver.class);
	beanDef.setSource(context.extractSource(resolverElement));
	beanDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
	MutablePropertyValues values = beanDef.getPropertyValues();

	List<Element> elements = DomUtils.getChildElementsByTagName(resolverElement, new String[] {"default-views"});
	if (!elements.isEmpty()) {
		ManagedList<Object> list = new ManagedList<Object>();
		for (Element element : DomUtils.getChildElementsByTagName(elements.get(0), "bean", "ref")) {
			list.add(context.getDelegate().parsePropertySubElement(element, null));
		}
		values.add("defaultViews", list);
	}
	if (resolverElement.hasAttribute("use-not-acceptable")) {
		values.add("useNotAcceptableStatusCode", resolverElement.getAttribute("use-not-acceptable"));
	}
	Object manager = MvcNamespaceUtils.getContentNegotiationManager(context);
	if (manager != null) {
		values.add("contentNegotiationManager", manager);
	}
	return beanDef;
}
 
Example #16
Source Project: blog_demos   Author: zq2599   File: BeanDefinitionParserDelegate.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Parse a property element.
 */
public void parsePropertyElement(Element ele, BeanDefinition bd) {
	String propertyName = ele.getAttribute(NAME_ATTRIBUTE);
	if (!StringUtils.hasLength(propertyName)) {
		error("Tag 'property' must have a 'name' attribute", ele);
		return;
	}
	this.parseState.push(new PropertyEntry(propertyName));
	try {
		if (bd.getPropertyValues().contains(propertyName)) {
			error("Multiple 'property' definitions for property '" + propertyName + "'", ele);
			return;
		}
		Object val = parsePropertyValue(ele, bd, propertyName);
		PropertyValue pv = new PropertyValue(propertyName, val);
		parseMetaElements(ele, pv);
		pv.setSource(extractSource(ele));
		bd.getPropertyValues().addPropertyValue(pv);
	}
	finally {
		this.parseState.pop();
	}
}
 
Example #17
Source Project: java-technology-stack   Author: codeEngraver   File: GenericTypeAwareAutowireCandidateResolver.java    License: MIT License 5 votes vote down vote up
@Nullable
protected RootBeanDefinition getResolvedDecoratedDefinition(RootBeanDefinition rbd) {
	BeanDefinitionHolder decDef = rbd.getDecoratedDefinition();
	if (decDef != null && this.beanFactory instanceof ConfigurableListableBeanFactory) {
		ConfigurableListableBeanFactory clbf = (ConfigurableListableBeanFactory) this.beanFactory;
		if (clbf.containsBeanDefinition(decDef.getBeanName())) {
			BeanDefinition dbd = clbf.getMergedBeanDefinition(decDef.getBeanName());
			if (dbd instanceof RootBeanDefinition) {
				return (RootBeanDefinition) dbd;
			}
		}
	}
	return null;
}
 
Example #18
Source Project: spring-analysis-note   Author: Vip-Augus   File: ProxyTransactionManagementConfiguration.java    License: MIT License 5 votes vote down vote up
@Bean(name = TransactionManagementConfigUtils.TRANSACTION_ADVISOR_BEAN_NAME)
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
public BeanFactoryTransactionAttributeSourceAdvisor transactionAdvisor() {
	BeanFactoryTransactionAttributeSourceAdvisor advisor = new BeanFactoryTransactionAttributeSourceAdvisor();
	advisor.setTransactionAttributeSource(transactionAttributeSource());
	advisor.setAdvice(transactionInterceptor());
	if (this.enableTx != null) {
		advisor.setOrder(this.enableTx.<Integer>getNumber("order"));
	}
	return advisor;
}
 
Example #19
Source Project: spring4-understanding   Author: langtianya   File: RoleAndDescriptionAnnotationTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void viaComponentScanning() {
	AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
	ctx.scan("org.springframework.context.annotation.role");
	ctx.refresh();
	assertThat("Expected bean to have ROLE_APPLICATION",
			ctx.getBeanDefinition("componentWithoutRole").getRole(), is(BeanDefinition.ROLE_APPLICATION));
	assertThat(ctx.getBeanDefinition("componentWithoutRole").getDescription(), is((Object) null));
	assertThat("Expected bean to have ROLE_INFRASTRUCTURE",
			ctx.getBeanDefinition("componentWithRole").getRole(), is(BeanDefinition.ROLE_INFRASTRUCTURE));
	assertThat(ctx.getBeanDefinition("componentWithRole").getDescription(), is("A Component with a role"));
}
 
Example #20
Source Project: blog_demos   Author: zq2599   File: BeanDefinitionReaderUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Generate a bean name for the given bean definition, unique within the
 * given bean factory.
 * @param definition the bean definition to generate a bean name for
 * @param registry the bean factory that the definition is going to be
 * registered with (to check for existing bean names)
 * @param isInnerBean whether the given bean definition will be registered
 * as inner bean or as top-level bean (allowing for special name generation
 * for inner beans versus top-level beans)
 * @return the generated bean name
 * @throws BeanDefinitionStoreException if no unique name can be generated
 * for the given bean definition
 */
public static String generateBeanName(
		BeanDefinition definition, BeanDefinitionRegistry registry, boolean isInnerBean)
		throws BeanDefinitionStoreException {

	String generatedBeanName = definition.getBeanClassName();
	if (generatedBeanName == null) {
		if (definition.getParentName() != null) {
			generatedBeanName = definition.getParentName() + "$child";
		}
		else if (definition.getFactoryBeanName() != null) {
			generatedBeanName = definition.getFactoryBeanName() + "$created";
		}
	}
	if (!StringUtils.hasText(generatedBeanName)) {
		throw new BeanDefinitionStoreException("Unnamed bean definition specifies neither " +
				"'class' nor 'parent' nor 'factory-bean' - can't generate bean name");
	}

	String id = generatedBeanName;
	if (isInnerBean) {
		// Inner bean: generate identity hashcode suffix.
		id = generatedBeanName + GENERATED_BEAN_NAME_SEPARATOR + ObjectUtils.getIdentityHexString(definition);
	}
	else {
		// Top-level bean: use plain class name.
		// Increase counter until the id is unique.
		int counter = -1;
		while (counter == -1 || registry.containsBeanDefinition(id)) {
			counter++;
			id = generatedBeanName + GENERATED_BEAN_NAME_SEPARATOR + counter;
		}
	}
	return id;
}
 
Example #21
Source Project: lams   Author: lamsfoundation   File: ScriptingDefaultsParser.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public BeanDefinition parse(Element element, ParserContext parserContext) {
	BeanDefinition bd =
			LangNamespaceUtils.registerScriptFactoryPostProcessorIfNecessary(parserContext.getRegistry());
	String refreshCheckDelay = element.getAttribute(REFRESH_CHECK_DELAY_ATTRIBUTE);
	if (StringUtils.hasText(refreshCheckDelay)) {
		bd.getPropertyValues().add("defaultRefreshCheckDelay", Long.valueOf(refreshCheckDelay));
	}
	String proxyTargetClass = element.getAttribute(PROXY_TARGET_CLASS_ATTRIBUTE);
	if (StringUtils.hasText(proxyTargetClass)) {
		bd.getPropertyValues().add("defaultProxyTargetClass", new TypedStringValue(proxyTargetClass, Boolean.class));
	}
	return null;
}
 
Example #22
Source Project: spring-native-query   Author: gasparbarancelli   File: NativeQueryBeanDefinition.java    License: MIT License 5 votes vote down vote up
static AbstractBeanDefinition of(Class<? extends NativeQuery> classe, Object source) {
    BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(classe.getName());
    builder.getRawBeanDefinition().setSource(source);
    builder.setLazyInit(false);
    builder.setScope(BeanDefinition.SCOPE_SINGLETON);
    AbstractBeanDefinition beanDefinition = builder.getBeanDefinition();
    beanDefinition.setInstanceSupplier(() -> source);
    beanDefinition.setAttribute("factoryBeanObjectType", classe.getName());
    return beanDefinition;
}
 
Example #23
Source Project: dorado   Author: javagossip   File: DoradoAutoConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
private String[] getSpringBootAppScanPackages() {
	BeanDefinitionRegistry registry = (BeanDefinitionRegistry) applicationContext;

	Set<String> packages = new HashSet<>();
	String[] names = registry.getBeanDefinitionNames();
	for (String name : names) {
		BeanDefinition definition = registry.getBeanDefinition(name);
		if (definition instanceof AnnotatedBeanDefinition) {
			AnnotatedBeanDefinition annotatedDefinition = (AnnotatedBeanDefinition) definition;
			addComponentScanningPackages(packages, annotatedDefinition.getMetadata());
		}
	}
	return packages.toArray(new String[] {});
}
 
Example #24
Source Project: spring-analysis-note   Author: Vip-Augus   File: Spr5475Tests.java    License: MIT License 5 votes vote down vote up
private void assertExceptionMessageForMisconfiguredFactoryMethod(BeanDefinition bd, String expectedMessage) {
	DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
	factory.registerBeanDefinition("foo", bd);

	try {
		factory.preInstantiateSingletons();
		fail("should have failed with BeanCreationException due to incorrectly invoked factory method");
	}
	catch (BeanCreationException ex) {
		assertThat(ex.getMessage(), equalTo(expectedMessage));
	}
}
 
Example #25
Source Project: java-technology-stack   Author: codeEngraver   File: BeanDefinitionReaderUtils.java    License: MIT License 5 votes vote down vote up
/**
 * Generate a bean name for the given bean definition, unique within the
 * given bean factory.
 * @param definition the bean definition to generate a bean name for
 * @param registry the bean factory that the definition is going to be
 * registered with (to check for existing bean names)
 * @param isInnerBean whether the given bean definition will be registered
 * as inner bean or as top-level bean (allowing for special name generation
 * for inner beans versus top-level beans)
 * @return the generated bean name
 * @throws BeanDefinitionStoreException if no unique name can be generated
 * for the given bean definition
 */
public static String generateBeanName(
		BeanDefinition definition, BeanDefinitionRegistry registry, boolean isInnerBean)
		throws BeanDefinitionStoreException {

	String generatedBeanName = definition.getBeanClassName();
	if (generatedBeanName == null) {
		if (definition.getParentName() != null) {
			generatedBeanName = definition.getParentName() + "$child";
		}
		else if (definition.getFactoryBeanName() != null) {
			generatedBeanName = definition.getFactoryBeanName() + "$created";
		}
	}
	if (!StringUtils.hasText(generatedBeanName)) {
		throw new BeanDefinitionStoreException("Unnamed bean definition specifies neither " +
				"'class' nor 'parent' nor 'factory-bean' - can't generate bean name");
	}

	String id = generatedBeanName;
	if (isInnerBean) {
		// Inner bean: generate identity hashcode suffix.
		id = generatedBeanName + GENERATED_BEAN_NAME_SEPARATOR + ObjectUtils.getIdentityHexString(definition);
	}
	else {
		// Top-level bean: use plain class name with unique suffix if necessary.
		return uniqueBeanName(generatedBeanName, registry);
	}
	return id;
}
 
Example #26
Source Project: java-technology-stack   Author: codeEngraver   File: BeanDefinitionParserDelegate.java    License: MIT License 5 votes vote down vote up
protected void parseCollectionElements(
		NodeList elementNodes, Collection<Object> target, @Nullable BeanDefinition bd, String defaultElementType) {

	for (int i = 0; i < elementNodes.getLength(); i++) {
		Node node = elementNodes.item(i);
		if (node instanceof Element && !nodeNameEquals(node, DESCRIPTION_ELEMENT)) {
			target.add(parsePropertySubElement((Element) node, bd, defaultElementType));
		}
	}
}
 
Example #27
Source Project: spring4-understanding   Author: langtianya   File: AnnotationDrivenJmsBeanDefinitionParser.java    License: Apache License 2.0 5 votes vote down vote up
private static void registerInfrastructureBean(
		ParserContext parserContext, BeanDefinitionBuilder builder, String beanName) {

	builder.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
	parserContext.getRegistry().registerBeanDefinition(beanName, builder.getBeanDefinition());
	BeanDefinitionHolder holder = new BeanDefinitionHolder(builder.getBeanDefinition(), beanName);
	parserContext.registerComponent(new BeanComponentDefinition(holder));
}
 
Example #28
Source Project: spring-s3-properties-loader   Author: ericdallo   File: S3PropertiesLocationRegistrarTest.java    License: MIT License 5 votes vote down vote up
@Test
public void shouldLoadPropertiesWhenThereisNoProfiles() {
	attributes.put("profiles", new String[] {});

	subject.registerBeanDefinitions(importingClassMetadata, registry);

	verify(registry).registerBeanDefinition(anyString(), any(BeanDefinition.class));
}
 
Example #29
Source Project: lams   Author: lamsfoundation   File: DefaultServletHandlerBeanDefinitionParser.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public BeanDefinition parse(Element element, ParserContext parserContext) {
	Object source = parserContext.extractSource(element);

	String defaultServletName = element.getAttribute("default-servlet-name");
	RootBeanDefinition defaultServletHandlerDef = new RootBeanDefinition(DefaultServletHttpRequestHandler.class);
	defaultServletHandlerDef.setSource(source);
	defaultServletHandlerDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
	if (StringUtils.hasText(defaultServletName)) {
		defaultServletHandlerDef.getPropertyValues().add("defaultServletName", defaultServletName);
	}
	String defaultServletHandlerName = parserContext.getReaderContext().generateBeanName(defaultServletHandlerDef);
	parserContext.getRegistry().registerBeanDefinition(defaultServletHandlerName, defaultServletHandlerDef);
	parserContext.registerComponent(new BeanComponentDefinition(defaultServletHandlerDef, defaultServletHandlerName));

	Map<String, String> urlMap = new ManagedMap<String, String>();
	urlMap.put("/**", defaultServletHandlerName);

	RootBeanDefinition handlerMappingDef = new RootBeanDefinition(SimpleUrlHandlerMapping.class);
	handlerMappingDef.setSource(source);
	handlerMappingDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
	handlerMappingDef.getPropertyValues().add("urlMap", urlMap);

	String handlerMappingBeanName = parserContext.getReaderContext().generateBeanName(handlerMappingDef);
	parserContext.getRegistry().registerBeanDefinition(handlerMappingBeanName, handlerMappingDef);
	parserContext.registerComponent(new BeanComponentDefinition(handlerMappingDef, handlerMappingBeanName));

	// Ensure BeanNameUrlHandlerMapping (SPR-8289) and default HandlerAdapters are not "turned off"
	MvcNamespaceUtils.registerDefaultComponents(parserContext, source);

	return null;
}
 
Example #30
Source Project: java-technology-stack   Author: codeEngraver   File: AspectJAutoProxyBeanDefinitionParser.java    License: MIT License 5 votes vote down vote up
private void extendBeanDefinition(Element element, ParserContext parserContext) {
	BeanDefinition beanDef =
			parserContext.getRegistry().getBeanDefinition(AopConfigUtils.AUTO_PROXY_CREATOR_BEAN_NAME);
	if (element.hasChildNodes()) {
		addIncludePatterns(element, parserContext, beanDef);
	}
}