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 File: DefaultsBeanDefinitionParser.java    From jdal with 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 #2
Source File: ViewResolversBeanDefinitionParser.java    From lams with 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 #3
Source File: ScheduledAnnotationBeanPostProcessorTests.java    From spring4-understanding with 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 #4
Source File: AnnotationDrivenCacheBeanDefinitionParser.java    From java-technology-stack with 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 #5
Source File: BeanDefinitionParserDelegate.java    From blog_demos with 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 #6
Source File: BeanDefinitionParserDelegate.java    From lams with 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 #7
Source File: RequiredAnnotationBeanPostProcessorTests.java    From spring-analysis-note with 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 #8
Source File: ValidIfExactlyOneNonNullCheckerTest.java    From cloudbreak with 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 #9
Source File: LiveBeansView.java    From java-technology-stack with 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 #10
Source File: BeanDefinitionParserDelegate.java    From lams with 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 #11
Source File: ResourcesBeanDefinitionParser.java    From lams with 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 #12
Source File: InjectAnnotationBeanPostProcessorTests.java    From spring4-understanding with 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 #13
Source File: DubboLoadBalancedRestTemplateAutoConfiguration.java    From spring-cloud-alibaba with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #14
Source File: BeanDefinitionDtoConverterServiceImpl.java    From geomajas-project-server with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 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 #15
Source File: LiveBeansView.java    From spring-analysis-note with 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 #16
Source File: AbstractAutowireCapableBeanFactory.java    From lams with 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 #17
Source File: StatefulFactory.java    From statefulj with Apache License 2.0 5 votes vote down vote up
private String registerFSM(
		ReferenceFactory referenceFactory,
		Class<?> statefulControllerClass,
		StatefulController scAnnotation,
		String persisterId,
		Class<?> managedClass,
		String finderId,
		Class<? extends Annotation> idAnnotationType,
		BeanDefinitionRegistry reg) {
	int retryAttempts = scAnnotation.retryAttempts();
	int retryInterval = scAnnotation.retryInterval();

	String fsmBeanId = referenceFactory.getFSMId();
	BeanDefinition fsmBean = BeanDefinitionBuilder
			.genericBeanDefinition(FSM.class)
			.getBeanDefinition();
	ConstructorArgumentValues args = fsmBean.getConstructorArgumentValues();
	args.addIndexedArgumentValue(0, fsmBeanId);
	args.addIndexedArgumentValue(1, new RuntimeBeanReference(persisterId));
	args.addIndexedArgumentValue(2, retryAttempts);
	args.addIndexedArgumentValue(3, retryInterval);
	args.addIndexedArgumentValue(4, managedClass);
	args.addIndexedArgumentValue(5, idAnnotationType);
	args.addIndexedArgumentValue(6, this.appContext);

	if (finderId != null) {
		args.addIndexedArgumentValue(7, new RuntimeBeanReference(finderId));
	}

	reg.registerBeanDefinition(fsmBeanId, fsmBean);
	return fsmBeanId;
}
 
Example #18
Source File: ScheduledAnnotationBeanPostProcessorTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test(expected = BeanCreationException.class)
public void nonVoidReturnType() {
	BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class);
	BeanDefinition targetDefinition = new RootBeanDefinition(NonVoidReturnTypeTestBean.class);
	context.registerBeanDefinition("postProcessor", processorDefinition);
	context.registerBeanDefinition("target", targetDefinition);
	context.refresh();
}
 
Example #19
Source File: ProxyJCacheConfiguration.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Bean(name = "jCacheInterceptor")
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
public JCacheInterceptor cacheInterceptor() {
	JCacheInterceptor interceptor = new JCacheInterceptor(this.errorHandler);
	interceptor.setCacheOperationSource(cacheOperationSource());
	return interceptor;
}
 
Example #20
Source File: ConfigurationManagerImpl.java    From zstack with Apache License 2.0 5 votes vote down vote up
private void handle(APIGenerateSqlVOViewMsg msg) {
    try {
        ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(true);
        scanner.addIncludeFilter(new AnnotationTypeFilter(EO.class));
        scanner.addExcludeFilter(new AnnotationTypeFilter(Controller.class));
        scanner.addExcludeFilter(new AnnotationTypeFilter(Component.class));
        StringBuilder sb = new StringBuilder();
        for (String pkg : msg.getBasePackageNames()) {
            for (BeanDefinition bd : scanner.findCandidateComponents(pkg)) {
                Class<?> entityClazz = Class.forName(bd.getBeanClassName());
                generateVOViewSql(sb, entityClazz);
            }
        }

        String exportPath = PathUtil.join(System.getProperty("user.home"), "zstack-mysql-view");
        FileUtils.deleteDirectory(new File(exportPath));
        File folder = new File(exportPath);
        folder.mkdirs();
        File outfile = new File(PathUtil.join(exportPath, "view.sql"));
        FileUtils.writeStringToFile(outfile, sb.toString());

        APIGenerateSqlVOViewEvent evt = new APIGenerateSqlVOViewEvent(msg.getId());
        bus.publish(evt);
    } catch (Exception e) {
        throw new CloudRuntimeException(e);
    }
}
 
Example #21
Source File: ColumnsBeanDefinitionParser.java    From jdal with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
	List<Object> columns = parserContext.getDelegate().parseListElement(element, builder.getRawBeanDefinition());
	builder.addPropertyValue("sourceList", columns);
	builder.addPropertyValue("targetListClass", ArrayList.class);
	builder.setScope(BeanDefinition.SCOPE_PROTOTYPE);
}
 
Example #22
Source File: SpringBeanDefinitionProxy.java    From Cleanstone with MIT License 5 votes vote down vote up
public void registerSimpleBean(String beanName, Class<?> beanClass) {
    final BeanDefinition beanDefinition = BeanDefinitionBuilder
            .rootBeanDefinition(beanClass)
            .setScope(BeanDefinition.SCOPE_PROTOTYPE)
            .getBeanDefinition();

    beanDefinitionRegistry.registerBeanDefinition(beanName, beanDefinition);
}
 
Example #23
Source File: RestResourceConfig.java    From Cheddar with Apache License 2.0 5 votes vote down vote up
private Collection<String> getResourceClassNames(final String[] packageNames) {

        final Collection<String> resourceClassNames = new ArrayList<>();
        for (final String packageName : packageNames) {
            for (final BeanDefinition bd : scanner.findCandidateComponents(packageName)) {
                resourceClassNames.add(bd.getBeanClassName());
            }
        }
        return resourceClassNames;
    }
 
Example #24
Source File: AspectJTransactionManagementConfiguration.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Bean(name = TransactionManagementConfigUtils.TRANSACTION_ASPECT_BEAN_NAME)
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
public AnnotationTransactionAspect transactionAspect() {
	AnnotationTransactionAspect txAspect = AnnotationTransactionAspect.aspectOf();
	if (this.txManager != null) {
		txAspect.setTransactionManager(this.txManager);
	}
	return txAspect;
}
 
Example #25
Source File: DetectorBeanConfiguration.java    From hub-detect with Apache License 2.0 5 votes vote down vote up
@Bean
@Scope(scopeName = BeanDefinition.SCOPE_PROTOTYPE)
public PipInspectorDetector pipInspectorBomTool(final DetectorEnvironment environment) {
    //final String requirementsFile = detectConfiguration.getProperty(DetectProperty.DETECT_PIP_REQUIREMENTS_PATH, PropertyAuthority.None);
    return new PipInspectorDetector(environment, detectConfiguration.getProperty(DetectProperty.DETECT_PIP_REQUIREMENTS_PATH, PropertyAuthority.None), detectFileFinder, pythonExecutableFinder(), pipInspectorManager(),
        pipInspectorExtractor());
}
 
Example #26
Source File: GenericTypeAwareAutowireCandidateResolver.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
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 #27
Source File: SampleTransactionManagementConfiguration.java    From spring-boot-graal-feature with Apache License 2.0 5 votes vote down vote up
@Bean(name = TransactionManagementConfigUtils.TRANSACTION_ADVISOR_BEAN_NAME)
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
public BeanFactoryTransactionAttributeSourceAdvisor transactionAdvisor(
		TransactionAttributeSource transactionAttributeSource,
		TransactionInterceptor transactionInterceptor) {
	BeanFactoryTransactionAttributeSourceAdvisor advisor = new BeanFactoryTransactionAttributeSourceAdvisor();
	advisor.setTransactionAttributeSource(transactionAttributeSource);
	advisor.setAdvice(transactionInterceptor);
	if (this.enableTx != null) {
		advisor.setOrder(this.enableTx.<Integer>getNumber("order"));
	}
	return advisor;
}
 
Example #28
Source File: ConfigurationBeanFactoryPostProcessor.java    From james-project with Apache License 2.0 5 votes vote down vote up
/**
 * Parse the configuration file and depending on it register the beans
 */
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {

    ConfigurationProvider confProvider = beanFactory.getBean(ConfigurationProvider.class);

    // loop over the beans
    for (String name : beans.keySet()) {

        try {

            HierarchicalConfiguration<ImmutableNode> config = confProvider.getConfiguration(name);

            // Get the configuration for the class
            String repClass = config.getString("[@class]");

            // Create the definition and register it
            BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
            BeanDefinition def = BeanDefinitionBuilder.genericBeanDefinition(repClass).getBeanDefinition();
            registry.registerBeanDefinition(name, def);

            String aliases = beans.get(name);
            String[] aliasArray = aliases.split(",");

            // check if we need to register some aliases for this bean
            if (aliasArray != null) {
                for (String anAliasArray : aliasArray) {
                    String alias = anAliasArray.trim();
                    if (alias.length() > 0) {
                        registry.registerAlias(name, anAliasArray);
                    }
                }
            }

        } catch (ConfigurationException e) {
            throw new FatalBeanException("Unable to parse configuration for bean " + name, e);
        }
    }

}
 
Example #29
Source File: ExtensionsAdminController.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
 * hmmm, does not work yet, how to get a list with all overwritten beans like the output from to the log.info
 * http://www.docjar.com/html/api/org/springframework/beans/factory/support/DefaultListableBeanFactory.java.html
 * 
 * @return
 */
private List getOverwrittenBeans() {
    final ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(CoreSpringFactory.servletContext);
    final XmlWebApplicationContext context = (XmlWebApplicationContext) applicationContext;
    final ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
    final String[] beanDefinitionNames = beanFactory.getBeanDefinitionNames();
    for (int i = 0; i < beanDefinitionNames.length; i++) {
        final String beanName = beanDefinitionNames[i];
        if (!beanName.contains("#")) {
            final BeanDefinition beanDef = beanFactory.getBeanDefinition(beanName);
            // System.out.println(beanDef.getOriginatingBeanDefinition());
        }
    }
    return null;
}
 
Example #30
Source File: ConfigurerImpl.java    From cxf with Apache License 2.0 5 votes vote down vote up
private void initWildcardDefinitionMap() {
    if (null != appContexts) {
        for (ApplicationContext appContext : appContexts) {
            for (String n : appContext.getBeanDefinitionNames()) {
                if (isWildcardBeanName(n)) {
                    AutowireCapableBeanFactory bf = appContext.getAutowireCapableBeanFactory();
                    BeanDefinitionRegistry bdr = (BeanDefinitionRegistry) bf;
                    BeanDefinition bd = bdr.getBeanDefinition(n);
                    String className = bd.getBeanClassName();
                    if (null != className) {
                        final String name = n.charAt(0) != '*' ? n
                                : "." + n.replaceAll("\\.", "\\."); //old wildcard
                        try {
                            Matcher matcher = Pattern.compile(name).matcher("");
                            List<MatcherHolder> m = wildCardBeanDefinitions.get(className);
                            if (m == null) {
                                m = new ArrayList<>();
                                wildCardBeanDefinitions.put(className, m);
                            }
                            MatcherHolder holder = new MatcherHolder(n, matcher);
                            m.add(holder);
                        } catch (PatternSyntaxException npe) {
                            //not a valid patter, we'll ignore
                        }
                    } else {
                        LogUtils.log(LOG, Level.WARNING, "WILDCARD_BEAN_ID_WITH_NO_CLASS_MSG", n);
                    }
                }
            }
        }
    }
}