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

The following examples show how to use org.springframework.beans.factory.support.GenericBeanDefinition. 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
private BeanDefinition createBeanDefinitionByIntrospection(Object object, NamedBeanMap refs,
		ConversionService conversionService) {
	validate(object);
	GenericBeanDefinition def = new GenericBeanDefinition();
	def.setBeanClass(object.getClass());
	MutablePropertyValues propertyValues = new MutablePropertyValues();
	for (PropertyDescriptor descriptor : BeanUtils.getPropertyDescriptors(object.getClass())) {
		if (descriptor.getWriteMethod() != null) {
			try {
				Object value = descriptor.getReadMethod().invoke(object, (Object[]) null);
				if (value != null) {
					if ("id".equals(descriptor.getName())) {

					} else {
						propertyValues.addPropertyValue(descriptor.getName(),
								createMetadataElementByIntrospection(value, refs, conversionService));
					}
				}
			} catch (Exception e) {
				// our contract says to ignore this property
			}
		}
	}
	def.setPropertyValues(propertyValues);
	return def;
}
 
Example 2
Source Project: spring-analysis-note   Source File: QualifierAnnotationTests.java    License: MIT License 6 votes vote down vote up
@Test
public void testQualifiedByParentValue() {
	StaticApplicationContext parent = new StaticApplicationContext();
	GenericBeanDefinition parentLarry = new GenericBeanDefinition();
	parentLarry.setBeanClass(Person.class);
	parentLarry.getPropertyValues().add("name", "ParentLarry");
	parentLarry.addQualifier(new AutowireCandidateQualifier(Qualifier.class, "parentLarry"));
	parent.registerBeanDefinition("someLarry", parentLarry);
	GenericBeanDefinition otherLarry = new GenericBeanDefinition();
	otherLarry.setBeanClass(Person.class);
	otherLarry.getPropertyValues().add("name", "OtherLarry");
	otherLarry.addQualifier(new AutowireCandidateQualifier(Qualifier.class, "otherLarry"));
	parent.registerBeanDefinition("someOtherLarry", otherLarry);
	parent.refresh();

	StaticApplicationContext context = new StaticApplicationContext(parent);
	BeanDefinitionReader reader = new XmlBeanDefinitionReader(context);
	reader.loadBeanDefinitions(CONFIG_LOCATION);
	context.registerSingleton("testBean", QualifiedByParentValueTestBean.class);
	context.refresh();
	QualifiedByParentValueTestBean testBean = (QualifiedByParentValueTestBean) context.getBean("testBean");
	Person person = testBean.getLarry();
	assertEquals("ParentLarry", person.getName());
}
 
Example 3
@Test
void retrieveResourceIdResolverBeanName_resourceIdResolverBeanAlreadyRegistered_resourceIdResolverBeanIsNotAgainRegistered() {
	// @checkstyle:on
	// Arrange
	BeanDefinition resourceIdResolverBeanDefinition = new GenericBeanDefinition();

	DefaultListableBeanFactory registry = new DefaultListableBeanFactory();
	registry.registerBeanDefinition(
			GlobalBeanDefinitionUtils.RESOURCE_ID_RESOLVER_BEAN_NAME,
			resourceIdResolverBeanDefinition);

	// Act
	GlobalBeanDefinitionUtils.retrieveResourceIdResolverBeanName(registry);

	// Assert
	assertThat(registry.getBeanDefinition(
			GlobalBeanDefinitionUtils.RESOURCE_ID_RESOLVER_BEAN_NAME))
					.isEqualTo(resourceIdResolverBeanDefinition);
}
 
Example 4
/**
 * 处理调用者
 * @param pluginRegistryInfo 插件注册的信息
 * @param callerClasses 调用者集合
 * @throws Exception 处理异常
 */
private void processCaller(PluginRegistryInfo pluginRegistryInfo, List<Class<?>> callerClasses) throws Exception {
    if(callerClasses == null || callerClasses.isEmpty()){
        return;
    }
    Set<String> beanNames = new HashSet<>();
    String pluginId = pluginRegistryInfo.getPluginWrapper().getPluginId();
    for (Class<?> callerClass : callerClasses) {
        Caller caller = callerClass.getAnnotation(Caller.class);
        if(caller == null){
            continue;
        }
        Object supper = applicationContext.getBean(caller.value());
        if(supper == null){
            return;
        }
        String beanName = springBeanRegister.register(pluginId, callerClass, (beanDefinition) ->{
            beanDefinition.getPropertyValues().add("callerInterface", callerClass);
            beanDefinition.getPropertyValues().add("supper", supper);
            beanDefinition.setBeanClass(CallerInterfaceFactory.class);
            beanDefinition.setAutowireMode(GenericBeanDefinition.AUTOWIRE_BY_TYPE);
        });
        beanNames.add(beanName);
    }
    pluginRegistryInfo.addProcessorInfo(getKey(KEY_CALLERS, pluginRegistryInfo), beanNames);
}
 
Example 5
@SuppressWarnings({ "unchecked", "rawtypes" })
public List<BeanDefinitionHolder> createBeans(Map<String, Object> parameters) throws RuntimeConfigException {
	GenericBeanDefinition def = new GenericBeanDefinition();
	def.setBeanClassName(className);
	MutablePropertyValues propertyValues = new MutablePropertyValues();
	List<NamedObject> namedObjects = new ArrayList<NamedObject>();
	if (checkCollection(BEAN_REFS, NamedObject.class, parameters) != Priority.NONE) {
		namedObjects.addAll((Collection) parameters.get(BEAN_REFS));
	}
	for (String name : parameters.keySet()) {
		if (!ignoredParams.contains(name)) {
			propertyValues.addPropertyValue(name, beanDefinitionDtoConverterService
					.createBeanMetadataElementByIntrospection(parameters.get(name), namedObjects));
		}
	}
	def.setPropertyValues(propertyValues);
	BeanDefinitionHolder holder = new BeanDefinitionHolder(def, (String) parameters.get(BEAN_NAME));
	List<BeanDefinitionHolder> holders = new ArrayList<BeanDefinitionHolder>();
	holders.add(holder);
	return holders;
}
 
Example 6
Source Project: java-technology-stack   Source File: QualifierAnnotationTests.java    License: MIT License 6 votes vote down vote up
@Test
public void testQualifiedByParentValue() {
	StaticApplicationContext parent = new StaticApplicationContext();
	GenericBeanDefinition parentLarry = new GenericBeanDefinition();
	parentLarry.setBeanClass(Person.class);
	parentLarry.getPropertyValues().add("name", "ParentLarry");
	parentLarry.addQualifier(new AutowireCandidateQualifier(Qualifier.class, "parentLarry"));
	parent.registerBeanDefinition("someLarry", parentLarry);
	GenericBeanDefinition otherLarry = new GenericBeanDefinition();
	otherLarry.setBeanClass(Person.class);
	otherLarry.getPropertyValues().add("name", "OtherLarry");
	otherLarry.addQualifier(new AutowireCandidateQualifier(Qualifier.class, "otherLarry"));
	parent.registerBeanDefinition("someOtherLarry", otherLarry);
	parent.refresh();

	StaticApplicationContext context = new StaticApplicationContext(parent);
	BeanDefinitionReader reader = new XmlBeanDefinitionReader(context);
	reader.loadBeanDefinitions(CONFIG_LOCATION);
	context.registerSingleton("testBean", QualifiedByParentValueTestBean.class);
	context.refresh();
	QualifiedByParentValueTestBean testBean = (QualifiedByParentValueTestBean) context.getBean("testBean");
	Person person = testBean.getLarry();
	assertEquals("ParentLarry", person.getName());
}
 
Example 7
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 8
Source Project: Aooms   Source File: DynamicDataSourceRegister.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) {
    Map<Object, Object> targetDataSources = new HashMap<Object, Object>();

    // 将主数据源添加到更多数据源中
    targetDataSources.put(AoomsVar.DEFAULT_DATASOURCE, defaultDataSource);
    DynamicDataSourceHolder.dataSourceIds.add(AoomsVar.DEFAULT_DATASOURCE);

    // 添加更多数据源
    targetDataSources.putAll(moreDataSources);
    for (String key : moreDataSources.keySet()) {
        DynamicDataSourceHolder.dataSourceIds.add(key);
    }

    // 创建DynamicDataSource
    GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
    beanDefinition.setBeanClass(DynamicDataSource.class);
    beanDefinition.setSynthetic(true);
    MutablePropertyValues mpv = beanDefinition.getPropertyValues();

    // 添加属性:AbstractRoutingDataSource.defaultTargetDataSource
    mpv.addPropertyValue("defaultTargetDataSource", defaultDataSource);
    mpv.addPropertyValue("targetDataSources", targetDataSources);

    beanDefinitionRegistry.registerBeanDefinition(AoomsVar.DEFAULT_DATASOURCE, beanDefinition);
}
 
Example 9
/**
 * Convert from a DTO to an internal Spring bean definition.
 * 
 * @param beanDefinitionDto The DTO object.
 * @return Returns a Spring bean definition.
 */
public BeanDefinition toInternal(BeanDefinitionInfo beanDefinitionInfo) {
	if (beanDefinitionInfo instanceof GenericBeanDefinitionInfo) {
		GenericBeanDefinitionInfo genericInfo = (GenericBeanDefinitionInfo) beanDefinitionInfo;
		GenericBeanDefinition def = new GenericBeanDefinition();
		def.setBeanClassName(genericInfo.getClassName());
		if (genericInfo.getPropertyValues() != null) {
			MutablePropertyValues propertyValues = new MutablePropertyValues();
			for (Entry<String, BeanMetadataElementInfo> entry : genericInfo.getPropertyValues().entrySet()) {
				BeanMetadataElementInfo info = entry.getValue();
				propertyValues.add(entry.getKey(), toInternal(info));
			}
			def.setPropertyValues(propertyValues);
		}
		return def;
	} else if (beanDefinitionInfo instanceof ObjectBeanDefinitionInfo) {
		ObjectBeanDefinitionInfo objectInfo = (ObjectBeanDefinitionInfo) beanDefinitionInfo;
		return createBeanDefinitionByIntrospection(objectInfo.getObject());
	} else {
		throw new IllegalArgumentException("Conversion to internal of " + beanDefinitionInfo.getClass().getName()
				+ " not implemented");
	}
}
 
Example 10
@Override
public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
    GenericBeanDefinition beanPostProcessorDefinition = new GenericBeanDefinition();
    beanPostProcessorDefinition.setInstanceSupplier(()->this);
    beanPostProcessorDefinition.setBeanClass(BeanPostProcessor.class);
    registry.registerBeanDefinition("NettyRpcClientBeanPostProcessor",beanPostProcessorDefinition);

    ClassPathScanningCandidateComponentProvider scanner = getScanner();
    scanner.setResourceLoader(resourceLoader);
    scanner.addIncludeFilter(new AnnotationTypeFilter(NettyRpcClient.class));
    Map<String, Object> enableNettyRpcClientsAttributes = metadata.getAnnotationAttributes(enableNettyRpcClientsCanonicalName);

    for (String basePackage : getBasePackages(metadata,enableNettyRpcClientsAttributes)) {
        for (BeanDefinition candidateComponent : scanner.findCandidateComponents(basePackage)) {
            if (!(candidateComponent instanceof AnnotatedBeanDefinition)) {
                continue;
            }

            AnnotatedBeanDefinition beanDefinition = (AnnotatedBeanDefinition) candidateComponent;
            if(!beanDefinition.getMetadata().isInterface()) {
                throw new IllegalArgumentException("@NettyRpcClient can only be specified on an interface");
            }
            registerNettyRpcClient(beanDefinition,registry);
        }
    }
}
 
Example 11
Source Project: engine   Source File: BeanDefinitionUtils.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Creates a bean definition for the specified bean name. If the parent context of the current context contains a
 * bean definition with the same name, the definition is created as a bean copy of the parent definition. This
 * method is useful for config parsers that want to create a bean definition from configuration but also want to
 * retain the default properties of the original bean.
 *
 * @param applicationContext    the current application context
 * @param beanName
 * @return the bean definition
 */
public static BeanDefinition createBeanDefinitionFromOriginal(ApplicationContext applicationContext,
                                                              String beanName) {
    ApplicationContext parentContext = applicationContext.getParent();
    BeanDefinition parentDefinition = null;

    if (parentContext != null &&
        parentContext.getAutowireCapableBeanFactory() instanceof ConfigurableListableBeanFactory) {
        ConfigurableListableBeanFactory parentBeanFactory = (ConfigurableListableBeanFactory)parentContext
            .getAutowireCapableBeanFactory();

        try {
            parentDefinition = parentBeanFactory.getBeanDefinition(beanName);
        } catch (NoSuchBeanDefinitionException e) {}
    }

    if (parentDefinition != null) {
        return new GenericBeanDefinition(parentDefinition);
    } else {
        return new GenericBeanDefinition();
    }
}
 
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: zxl   Source File: MulCommonBaseServiceParser.java    License: Apache License 2.0 6 votes vote down vote up
private BeanDefinition buildSessionFactoryBeanDefinition(Element element, String name, BeanDefinitionParserDelegate beanDefinitionParserDelegate, BeanDefinitionRegistry beanDefinitionRegistry) {
	AbstractBeanDefinition beanDefinition = new GenericBeanDefinition();
	beanDefinition.setAttribute(ID_ATTRIBUTE, name + SESSION_FACTORY_SUFFIX);
	beanDefinition.setBeanClass(LocalSessionFactoryBean.class);
	beanDefinition.setParentName(SESSION_FACTORY_PARENT_BEAN_NAME);
	MutablePropertyValues propertyValues = new MutablePropertyValues();
	propertyValues.add("dataSource", new RuntimeBeanReference(name + DATA_SOURCE_SUFFIX));
	if (element.hasAttribute(TABLE_PREFIX_NAME) && !StringUtil.isEmpty(element.getAttribute(TABLE_PREFIX_NAME))) {
		AbstractBeanDefinition namingStrategyBeanDefinition = new GenericBeanDefinition();
		String randomBeanName = UUID.randomUUID().toString();
		namingStrategyBeanDefinition.setAttribute(ID_ATTRIBUTE, randomBeanName);
		namingStrategyBeanDefinition.setBeanClass(HibernateNamingStrategy.class);
		MutablePropertyValues mutablePropertyValues = new MutablePropertyValues();
		mutablePropertyValues.add("prefix", element.getAttribute(TABLE_PREFIX_NAME));
		namingStrategyBeanDefinition.setPropertyValues(mutablePropertyValues);
		beanDefinitionRegistry.registerBeanDefinition(randomBeanName, namingStrategyBeanDefinition);
		propertyValues.addPropertyValue("namingStrategy", new RuntimeBeanReference(randomBeanName));
	}
	beanDefinition.setPropertyValues(propertyValues);
	beanDefinitionParserDelegate.parsePropertyElements(element, beanDefinition);
	return beanDefinition;
}
 
Example 14
Source Project: tsharding   Source File: DataSourceScanner.java    License: MIT License 6 votes vote down vote up
/**
 * 将数据源注入到Spring中
 *
 * @param registry
 * @param dataSourcesMapping
 */
private void registerDataSources(BeanDefinitionRegistry registry,
                                 Map<String, Map<DataSourceType, DataSource>> dataSourcesMapping) {

    for (Map.Entry<String, Map<DataSourceType, DataSource>> entry : dataSourcesMapping.entrySet()) {
        final String name = entry.getKey();
        for (Map.Entry<DataSourceType, DataSource> subEntry : entry.getValue().entrySet()) {
            GenericBeanDefinition dataSourceBeanDefinition = new GenericBeanDefinition();
            dataSourceBeanDefinition.setBeanClass(DataSourceFactoryBean.class);
            ConstructorArgumentValues constructorArgumentValues = new ConstructorArgumentValues();
            constructorArgumentValues.addIndexedArgumentValue(0, subEntry.getValue());
            dataSourceBeanDefinition.setConstructorArgumentValues(constructorArgumentValues);
            String beanName = name + Character.toUpperCase(subEntry.getKey().name().charAt(0))
                    + subEntry.getKey().name().substring(1) + "DataSource";
            registry.registerBeanDefinition(beanName, dataSourceBeanDefinition);
        }
    }
}
 
Example 15
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 16
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 17
Source Project: blog_demos   Source File: GroovyBeanDefinitionWrapper.java    License: Apache License 2.0 6 votes vote down vote up
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 18
Source Project: zxl   Source File: MulCommonBaseServiceParser.java    License: Apache License 2.0 5 votes vote down vote up
private BeanDefinition buildDataSourceBeanDefinition(Element element, String name) {
	AbstractBeanDefinition beanDefinition = new GenericBeanDefinition();
	beanDefinition.setAttribute(ID_ATTRIBUTE, name + DATA_SOURCE_SUFFIX);
	beanDefinition.setBeanClass(SimpleDataSource.class);
	MutablePropertyValues propertyValues = new MutablePropertyValues();
	propertyValues.add("name", name);
	beanDefinition.setPropertyValues(propertyValues);
	return beanDefinition;
}
 
Example 19
@Override
@Nullable
public final TargetSource getTargetSource(Class<?> beanClass, String beanName) {
	AbstractBeanFactoryBasedTargetSource targetSource =
			createBeanFactoryBasedTargetSource(beanClass, beanName);
	if (targetSource == null) {
		return null;
	}

	if (logger.isDebugEnabled()) {
		logger.debug("Configuring AbstractBeanFactoryBasedTargetSource: " + targetSource);
	}

	DefaultListableBeanFactory internalBeanFactory = getInternalBeanFactoryForBean(beanName);

	// We need to override just this bean definition, as it may reference other beans
	// and we're happy to take the parent's definition for those.
	// Always use prototype scope if demanded.
	BeanDefinition bd = this.beanFactory.getMergedBeanDefinition(beanName);
	GenericBeanDefinition bdCopy = new GenericBeanDefinition(bd);
	if (isPrototypeBased()) {
		bdCopy.setScope(BeanDefinition.SCOPE_PROTOTYPE);
	}
	internalBeanFactory.registerBeanDefinition(beanName, bdCopy);

	// Complete configuring the PrototypeTargetSource.
	targetSource.setTargetBeanName(beanName);
	targetSource.setBeanFactory(internalBeanFactory);

	return targetSource;
}
 
Example 20
Source Project: spring-analysis-note   Source File: ScriptFactoryPostProcessor.java    License: MIT License 5 votes vote down vote up
/**
 * Create a bean definition for the scripted object, based on the given script
 * definition, extracting the definition data that is relevant for the scripted
 * object (that is, everything but bean class and constructor arguments).
 * @param bd the full script bean definition
 * @param scriptFactoryBeanName the name of the internal ScriptFactory bean
 * @param scriptSource the ScriptSource for the scripted bean
 * @param interfaces the interfaces that the scripted bean is supposed to implement
 * @return the extracted ScriptFactory bean definition
 * @see org.springframework.scripting.ScriptFactory#getScriptedObject
 */
protected BeanDefinition createScriptedObjectBeanDefinition(BeanDefinition bd, String scriptFactoryBeanName,
		ScriptSource scriptSource, @Nullable Class<?>[] interfaces) {

	GenericBeanDefinition objectBd = new GenericBeanDefinition(bd);
	objectBd.setFactoryBeanName(scriptFactoryBeanName);
	objectBd.setFactoryMethodName("getScriptedObject");
	objectBd.getConstructorArgumentValues().clear();
	objectBd.getConstructorArgumentValues().addIndexedArgumentValue(0, scriptSource);
	objectBd.getConstructorArgumentValues().addIndexedArgumentValue(1, interfaces);
	return objectBd;
}
 
Example 21
Source Project: spring-analysis-note   Source File: StaticApplicationContext.java    License: MIT License 5 votes vote down vote up
/**
 * Register a singleton bean with the underlying bean factory.
 * <p>For more advanced needs, register with the underlying BeanFactory directly.
 * @see #getDefaultListableBeanFactory
 */
public void registerSingleton(String name, Class<?> clazz, MutablePropertyValues pvs) throws BeansException {
	GenericBeanDefinition bd = new GenericBeanDefinition();
	bd.setBeanClass(clazz);
	bd.setPropertyValues(pvs);
	getDefaultListableBeanFactory().registerBeanDefinition(name, bd);
}
 
Example 22
Source Project: spring-analysis-note   Source File: StaticApplicationContext.java    License: MIT License 5 votes vote down vote up
/**
 * Register a prototype bean with the underlying bean factory.
 * <p>For more advanced needs, register with the underlying BeanFactory directly.
 * @see #getDefaultListableBeanFactory
 */
public void registerPrototype(String name, Class<?> clazz) throws BeansException {
	GenericBeanDefinition bd = new GenericBeanDefinition();
	bd.setScope(GenericBeanDefinition.SCOPE_PROTOTYPE);
	bd.setBeanClass(clazz);
	getDefaultListableBeanFactory().registerBeanDefinition(name, bd);
}
 
Example 23
Source Project: spring-analysis-note   Source File: StaticApplicationContext.java    License: MIT License 5 votes vote down vote up
/**
 * Register a prototype bean with the underlying bean factory.
 * <p>For more advanced needs, register with the underlying BeanFactory directly.
 * @see #getDefaultListableBeanFactory
 */
public void registerPrototype(String name, Class<?> clazz, MutablePropertyValues pvs) throws BeansException {
	GenericBeanDefinition bd = new GenericBeanDefinition();
	bd.setScope(GenericBeanDefinition.SCOPE_PROTOTYPE);
	bd.setBeanClass(clazz);
	bd.setPropertyValues(pvs);
	getDefaultListableBeanFactory().registerBeanDefinition(name, bd);
}
 
Example 24
Source Project: spring-content   Source File: StoreUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static Set<GenericBeanDefinition> getStoreCandidates(Environment env, ResourceLoader loader, String[] basePackages, boolean multiStoreMode, Class<?>[] identifyingType) {

		StoreCandidateComponentProvider scanner = new StoreCandidateComponentProvider(false, env);
		// scanner.setConsiderNestedRepositoryInterfaces(shouldConsiderNestedRepositories());
		scanner.setResourceLoader(loader);
		// scanner.setEnvironment(environment);

		/*
		 * for (TypeFilter filter : getExcludeFilters()) {
		 * scanner.addExcludeFilter(filter); }
		 */

		Set<GenericBeanDefinition> result = new HashSet<>();

		for (String basePackage : basePackages) {
			Set<BeanDefinition> candidates = scanner.findCandidateComponents(basePackage);
			for (BeanDefinition candidate : candidates) {

				boolean qualifiedForImplementation = !multiStoreMode || isStrictRepositoryCandidate(identifyingType, candidate.getBeanClassName(), loader);
				if (qualifiedForImplementation) {
					result.add((GenericBeanDefinition)candidate);
				}
			}
		}

		return result;
	}
 
Example 25
Source Project: disconf   Source File: DisconfMgrBean.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * register aspectJ for disconf get request
 *
 * @param registry
 */
private void registerAspect(BeanDefinitionRegistry registry) {

    GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
    beanDefinition.setBeanClass(DisconfAspectJ.class);
    beanDefinition.setLazyInit(false);
    beanDefinition.setAbstract(false);
    beanDefinition.setAutowireCandidate(true);
    beanDefinition.setScope("singleton");

    registry.registerBeanDefinition("disconfAspectJ", beanDefinition);
}
 
Example 26
private WebApplicationContext initApplicationContext(String scope) {
	MockServletContext sc = new MockServletContext();
	GenericWebApplicationContext ac = new GenericWebApplicationContext(sc);
	GenericBeanDefinition bd = new GenericBeanDefinition();
	bd.setBeanClass(DerivedTestBean.class);
	bd.setScope(scope);
	ac.registerBeanDefinition(NAME, bd);
	ac.refresh();
	return ac;
}
 
Example 27
private GenericBeanDefinition createObjectMapperFactoryDefinition(@Nullable Object source) {
	GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
	beanDefinition.setBeanClass(Jackson2ObjectMapperFactoryBean.class);
	beanDefinition.setSource(source);
	beanDefinition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
	return beanDefinition;
}
 
Example 28
private RuntimeBeanReference registerMessageConverter(
		Element element, ParserContext context, @Nullable Object source) {

	Element convertersElement = DomUtils.getChildElementByTagName(element, "message-converters");
	ManagedList<Object> converters = new ManagedList<>();
	if (convertersElement != null) {
		converters.setSource(source);
		for (Element beanElement : DomUtils.getChildElementsByTagName(convertersElement, "bean", "ref")) {
			Object object = context.getDelegate().parsePropertySubElement(beanElement, null);
			converters.add(object);
		}
	}
	if (convertersElement == null || Boolean.valueOf(convertersElement.getAttribute("register-defaults"))) {
		converters.setSource(source);
		converters.add(new RootBeanDefinition(StringMessageConverter.class));
		converters.add(new RootBeanDefinition(ByteArrayMessageConverter.class));
		if (jackson2Present) {
			RootBeanDefinition jacksonConverterDef = new RootBeanDefinition(MappingJackson2MessageConverter.class);
			RootBeanDefinition resolverDef = new RootBeanDefinition(DefaultContentTypeResolver.class);
			resolverDef.getPropertyValues().add("defaultMimeType", MimeTypeUtils.APPLICATION_JSON);
			jacksonConverterDef.getPropertyValues().add("contentTypeResolver", resolverDef);
			// Use Jackson factory in order to have JSR-310 and Joda-Time modules registered automatically
			GenericBeanDefinition jacksonFactoryDef = new GenericBeanDefinition();
			jacksonFactoryDef.setBeanClass(Jackson2ObjectMapperFactoryBean.class);
			jacksonFactoryDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
			jacksonFactoryDef.setSource(source);
			jacksonConverterDef.getPropertyValues().add("objectMapper", jacksonFactoryDef);
			converters.add(jacksonConverterDef);
		}
	}
	ConstructorArgumentValues cargs = new ConstructorArgumentValues();
	cargs.addIndexedArgumentValue(0, converters);
	RootBeanDefinition messageConverterDef = new RootBeanDefinition(CompositeMessageConverter.class, cargs, null);
	String name = MESSAGE_CONVERTER_BEAN_NAME;
	registerBeanDefByName(name, messageConverterDef, context, source);
	return new RuntimeBeanReference(name);
}
 
Example 29
@Test
public void testIncompleteBeanDefinition() {
	bf.registerBeanDefinition("testBean", new GenericBeanDefinition());
	try {
		bf.getBean("testBean");
		fail("Should have thrown BeanCreationException");
	}
	catch (BeanCreationException ex) {
		assertTrue(ex.getRootCause() instanceof IllegalStateException);
	}
}
 
Example 30
@Test
public void testIncompleteBeanDefinition() {
	bf.registerBeanDefinition("testBean", new GenericBeanDefinition());
	try {
		bf.getBean("testBean");
	}
	catch (BeanCreationException ex) {
		assertTrue(ex.getRootCause() instanceof IllegalStateException);
	}
}