Java Code Examples for org.springframework.beans.factory.config.BeanDefinition#setScope()

The following examples show how to use org.springframework.beans.factory.config.BeanDefinition#setScope() . 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
/**
 * 方法描述 初始化spring bean
 * @method initBean
 */
public void initBean(){
    for (Map.Entry<String, Class> entry : cacheClassMap.entrySet()) {
        String className = entry.getKey();
        Class<?> cla = entry.getValue();
        if(isSpringBeanClass(cla)){
            BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(cla);
            BeanDefinition beanDefinition = beanDefinitionBuilder.getRawBeanDefinition();
            //设置当前bean定义对象是单利的
            beanDefinition.setScope("singleton");

            //将变量首字母置小写
            String beanName = StringUtils.uncapitalize(className);

            beanName =  beanName.substring(beanName.lastIndexOf(".")+1);
            beanName = StringUtils.uncapitalize(beanName);

            registeredBean.add(beanName);
            System.out.println("注册bean:"+beanName);
        }
    }
}
 
Example 2
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry)
		throws BeansException {
	bindEnvironmentIfNeeded(registry);
	for (String name : registry.getBeanDefinitionNames()) {
		BeanDefinition definition = registry.getBeanDefinition(name);
		if (isApplicable(registry, name, definition)) {
			BeanDefinitionHolder holder = new BeanDefinitionHolder(definition,
					name);
			BeanDefinitionHolder proxy = ScopedProxyUtils
					.createScopedProxy(holder, registry, true);
			definition.setScope("refresh");
			if (registry.containsBeanDefinition(proxy.getBeanName())) {
				registry.removeBeanDefinition(proxy.getBeanName());
			}
			registry.registerBeanDefinition(proxy.getBeanName(),
					proxy.getBeanDefinition());
		}
	}
}
 
Example 3
public Set<BeanDefinitionHolder> doScan(String... basePackages) {
  Assert.notEmpty(basePackages, "At least one base package must be specified");
  Set<BeanDefinitionHolder> beanDefinitions = new LinkedHashSet<>();
  for (String basePackage : basePackages) {
    Set<BeanDefinition> candidates = findCandidateComponents(basePackage);
    for (BeanDefinition candidate : candidates) {
      ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(candidate);
      candidate.setScope(scopeMetadata.getScopeName());
      String beanName = this.beanNameGenerator.generateBeanName(candidate, this.getRegistry());
      if (candidate instanceof AbstractBeanDefinition) {
        postProcessBeanDefinition((AbstractBeanDefinition) candidate, beanName);
      }
      if (candidate instanceof AnnotatedBeanDefinition) {
        AnnotationConfigUtils.processCommonDefinitionAnnotations((AnnotatedBeanDefinition) candidate);
      }
      if (checkCandidate(beanName, candidate)) {
        BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(candidate, beanName);
        beanDefinitions.add(definitionHolder);
      }
    }
  }
  return beanDefinitions;
}
 
Example 4
/**
 * Perform a scan within the specified base packages,
 * returning the registered bean definitions.
 * <p>This method does <i>not</i> register an annotation config processor
 * but rather leaves this up to the caller.
 * @param basePackages the packages to check for annotated classes
 * @return set of beans registered if any for tooling registration purposes (never {@code null})
 */
protected Set<BeanDefinitionHolder> doScan(String... basePackages) {
	Assert.notEmpty(basePackages, "At least one base package must be specified");
	Set<BeanDefinitionHolder> beanDefinitions = new LinkedHashSet<BeanDefinitionHolder>();
	for (String basePackage : basePackages) {
		Set<BeanDefinition> candidates = findCandidateComponents(basePackage);
		for (BeanDefinition candidate : candidates) {
			ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(candidate);
			candidate.setScope(scopeMetadata.getScopeName());
			String beanName = this.beanNameGenerator.generateBeanName(candidate, this.registry);
			if (candidate instanceof AbstractBeanDefinition) {
				postProcessBeanDefinition((AbstractBeanDefinition) candidate, beanName);
			}
			if (candidate instanceof AnnotatedBeanDefinition) {
				AnnotationConfigUtils.processCommonDefinitionAnnotations((AnnotatedBeanDefinition) candidate);
			}
			if (checkCandidate(beanName, candidate)) {
				BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(candidate, beanName);
				definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
				beanDefinitions.add(definitionHolder);
				registerBeanDefinition(definitionHolder, this.registry);
			}
		}
	}
	return beanDefinitions;
}
 
Example 5
/**
 * Checks how is bean defined and deduces scope name from JSF CDI annotations.
 *
 * @param definition beanDefinition
 */
private void registerJsfCdiToSpring(BeanDefinition definition) {

	if (definition instanceof AnnotatedBeanDefinition) {
		AnnotatedBeanDefinition annDef = (AnnotatedBeanDefinition) definition;

		String scopeName = null;
		// firstly check whether bean is defined via configuration
		if (annDef.getFactoryMethodMetadata() != null) {
			scopeName = deduceScopeName(annDef.getFactoryMethodMetadata());
		}
		else {
			// fallback to type
			scopeName = deduceScopeName(annDef.getMetadata());
		}

		if (scopeName != null) {
			definition.setScope(scopeName);

			log.debug("{} - Scope({})", definition.getBeanClassName(), scopeName.toUpperCase());
		}
	}
}
 
Example 6
/**
 * Prepare the script beans in the internal BeanFactory that this
 * post-processor uses. Each original bean definition will be split
 * into a ScriptFactory definition and a scripted object definition.
 * @param bd the original bean definition in the main BeanFactory
 * @param scriptFactoryBeanName the name of the internal ScriptFactory bean
 * @param scriptedObjectBeanName the name of the internal scripted object bean
 */
protected void prepareScriptBeans(BeanDefinition bd, String scriptFactoryBeanName, String scriptedObjectBeanName) {
	// Avoid recreation of the script bean definition in case of a prototype.
	synchronized (this.scriptBeanFactory) {
		if (!this.scriptBeanFactory.containsBeanDefinition(scriptedObjectBeanName)) {

			this.scriptBeanFactory.registerBeanDefinition(
					scriptFactoryBeanName, createScriptFactoryBeanDefinition(bd));
			ScriptFactory scriptFactory =
					this.scriptBeanFactory.getBean(scriptFactoryBeanName, ScriptFactory.class);
			ScriptSource scriptSource =
					getScriptSource(scriptFactoryBeanName, scriptFactory.getScriptSourceLocator());
			Class<?>[] interfaces = scriptFactory.getScriptInterfaces();

			Class<?>[] scriptedInterfaces = interfaces;
			if (scriptFactory.requiresConfigInterface() && !bd.getPropertyValues().isEmpty()) {
				Class<?> configInterface = createConfigInterface(bd, interfaces);
				scriptedInterfaces = ObjectUtils.addObjectToArray(interfaces, configInterface);
			}

			BeanDefinition objectBd = createScriptedObjectBeanDefinition(
					bd, scriptFactoryBeanName, scriptSource, scriptedInterfaces);
			long refreshCheckDelay = resolveRefreshCheckDelay(bd);
			if (refreshCheckDelay >= 0) {
				objectBd.setScope(BeanDefinition.SCOPE_PROTOTYPE);
			}

			this.scriptBeanFactory.registerBeanDefinition(scriptedObjectBeanName, objectBd);
		}
	}
}
 
Example 7
/**
 * Perform a scan within the specified base packages,
 * returning the registered bean definitions.
 * <p>This method does <i>not</i> register an annotation config processor
 * but rather leaves this up to the caller.
 * @param basePackages the packages to check for annotated classes
 * @return set of beans registered if any for tooling registration purposes (never {@code null})
 */
protected Set<BeanDefinitionHolder> doScan(String... basePackages) {
	Assert.notEmpty(basePackages, "At least one base package must be specified");
	Set<BeanDefinitionHolder> beanDefinitions = new LinkedHashSet<>();
	for (String basePackage : basePackages) {
		Set<BeanDefinition> candidates = findCandidateComponents(basePackage);
		for (BeanDefinition candidate : candidates) {
			ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(candidate);
			candidate.setScope(scopeMetadata.getScopeName());
			String beanName = this.beanNameGenerator.generateBeanName(candidate, this.registry);
			if (candidate instanceof AbstractBeanDefinition) {
				postProcessBeanDefinition((AbstractBeanDefinition) candidate, beanName);
			}
			if (candidate instanceof AnnotatedBeanDefinition) {
				AnnotationConfigUtils.processCommonDefinitionAnnotations((AnnotatedBeanDefinition) candidate);
			}
			if (checkCandidate(beanName, candidate)) {
				BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(candidate, beanName);
				definitionHolder =
						AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
				beanDefinitions.add(definitionHolder);
				registerBeanDefinition(definitionHolder, this.registry);
			}
		}
	}
	return beanDefinitions;
}
 
Example 8
/**
 * Prepare the script beans in the internal BeanFactory that this
 * post-processor uses. Each original bean definition will be split
 * into a ScriptFactory definition and a scripted object definition.
 * @param bd the original bean definition in the main BeanFactory
 * @param scriptFactoryBeanName the name of the internal ScriptFactory bean
 * @param scriptedObjectBeanName the name of the internal scripted object bean
 */
protected void prepareScriptBeans(BeanDefinition bd, String scriptFactoryBeanName, String scriptedObjectBeanName) {
	// Avoid recreation of the script bean definition in case of a prototype.
	synchronized (this.scriptBeanFactory) {
		if (!this.scriptBeanFactory.containsBeanDefinition(scriptedObjectBeanName)) {

			this.scriptBeanFactory.registerBeanDefinition(
					scriptFactoryBeanName, createScriptFactoryBeanDefinition(bd));
			ScriptFactory scriptFactory =
					this.scriptBeanFactory.getBean(scriptFactoryBeanName, ScriptFactory.class);
			ScriptSource scriptSource =
					getScriptSource(scriptFactoryBeanName, scriptFactory.getScriptSourceLocator());
			Class<?>[] interfaces = scriptFactory.getScriptInterfaces();

			Class<?>[] scriptedInterfaces = interfaces;
			if (scriptFactory.requiresConfigInterface() && !bd.getPropertyValues().isEmpty()) {
				Class<?> configInterface = createConfigInterface(bd, interfaces);
				scriptedInterfaces = ObjectUtils.addObjectToArray(interfaces, configInterface);
			}

			BeanDefinition objectBd = createScriptedObjectBeanDefinition(
					bd, scriptFactoryBeanName, scriptSource, scriptedInterfaces);
			long refreshCheckDelay = resolveRefreshCheckDelay(bd);
			if (refreshCheckDelay >= 0) {
				objectBd.setScope(BeanDefinition.SCOPE_PROTOTYPE);
			}

			this.scriptBeanFactory.registerBeanDefinition(scriptedObjectBeanName, objectBd);
		}
	}
}
 
Example 9
/**
 * Perform a scan within the specified base packages,
 * returning the registered bean definitions.
 * <p>This method does <i>not</i> register an annotation config processor
 * but rather leaves this up to the caller.
 * @param basePackages the packages to check for annotated classes
 * @return set of beans registered if any for tooling registration purposes (never {@code null})
 */
protected Set<BeanDefinitionHolder> doScan(String... basePackages) {
	Assert.notEmpty(basePackages, "At least one base package must be specified");
	Set<BeanDefinitionHolder> beanDefinitions = new LinkedHashSet<>();
	for (String basePackage : basePackages) {
		Set<BeanDefinition> candidates = findCandidateComponents(basePackage);
		for (BeanDefinition candidate : candidates) {
			ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(candidate);
			candidate.setScope(scopeMetadata.getScopeName());
			String beanName = this.beanNameGenerator.generateBeanName(candidate, this.registry);
			if (candidate instanceof AbstractBeanDefinition) {
				postProcessBeanDefinition((AbstractBeanDefinition) candidate, beanName);
			}
			if (candidate instanceof AnnotatedBeanDefinition) {
				AnnotationConfigUtils.processCommonDefinitionAnnotations((AnnotatedBeanDefinition) candidate);
			}
			if (checkCandidate(beanName, candidate)) {
				BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(candidate, beanName);
				definitionHolder =
						AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
				beanDefinitions.add(definitionHolder);
				registerBeanDefinition(definitionHolder, this.registry);
			}
		}
	}
	return beanDefinitions;
}
 
Example 10
Source Project: pacbot   File: RefreshScopeConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory factory)
        throws BeansException {
    for (String beanName : factory.getBeanDefinitionNames()) {
        BeanDefinition beanDef = factory.getBeanDefinition(beanName);
        if (beanDef.getBeanClassName() != null
                && beanDef.getBeanClassName().startsWith(
                        "com.tmobile.pacman")) {
            beanDef.setScope("refresh");
        }
    }
}
 
Example 11
Source Project: pacbot   File: RefreshScopeConfig.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Overriding to update the test scope. 
 * 
 */
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory factory) {
    for (String beanName : factory.getBeanDefinitionNames()) {
        BeanDefinition beanDef = factory.getBeanDefinition(beanName);
        if (beanDef.getBeanClassName() != null && beanDef.getBeanClassName().startsWith("com.tmobile.pacman")) {
            beanDef.setScope("refresh");
        }
    }
}
 
Example 12
Source Project: pacbot   File: RefreshScopeConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory factory) throws BeansException {
	for (String beanName : factory.getBeanDefinitionNames()) {
		BeanDefinition beanDef = factory.getBeanDefinition(beanName);
		if(beanDef.getBeanClassName()!=null && beanDef.getBeanClassName().startsWith("com.tmobile.pacman")) {
			beanDef.setScope("refresh");
		}
	}
}
 
Example 13
Source Project: pacbot   File: RefreshScopeConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory factory) throws BeansException {
	for (String beanName : factory.getBeanDefinitionNames()) {
		BeanDefinition beanDef = factory.getBeanDefinition(beanName);
		if (beanDef.getBeanClassName() != null && beanDef.getBeanClassName().startsWith("com.tmobile.pacman")
				&& !beanDef.getBeanClassName().startsWith("com.tmobile.pacman.api.notification.config.PacmanQuartzConfiguration")) {
			beanDef.setScope("refresh");
		}
	}
}
 
Example 14
Source Project: pacbot   File: RefreshScopeConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory factory) {
    for (String beanName : factory.getBeanDefinitionNames()) {
        BeanDefinition beanDef = factory.getBeanDefinition(beanName);
        if (beanDef.getBeanClassName() != null && beanDef.getBeanClassName().startsWith("com.tmobile.pacman")) {
            beanDef.setScope("refresh");
        }
    }
}
 
Example 15
Source Project: happor   File: HapporSpringContext.java    License: MIT License 5 votes vote down vote up
private void registerController(Class<? extends HttpController> clazz) {
	String name = "controller#" + getControllers().size();
	BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(clazz);
	BeanDefinition beanDefinition = builder.getBeanDefinition();
	beanDefinition.setScope("prototype");
	BeanDefinitionRegistry factory = (BeanDefinitionRegistry) ctx.getBeanFactory();
	factory.registerBeanDefinition(name, beanDefinition);
}
 
Example 16
/**
 * Resolve candidate to a bean definition and (re)load in Spring.
 * Synchronize to avoid parallel bean definition - usually on reload the beans are interrelated
 * and parallel load will cause concurrent modification exception.
 *
 * @param candidate the candidate to reload
 */
public void defineBean(BeanDefinition candidate) {
    synchronized (getClass()) { // TODO sychronize on DefaultListableFactory.beanDefinitionMap?

        ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(candidate);
        candidate.setScope(scopeMetadata.getScopeName());
        String beanName = this.beanNameGenerator.generateBeanName(candidate, registry);

        if (candidate instanceof AbstractBeanDefinition) {
            postProcessBeanDefinition((AbstractBeanDefinition) candidate, beanName);
        }
        if (candidate instanceof AnnotatedBeanDefinition) {
            processCommonDefinitionAnnotations((AnnotatedBeanDefinition) candidate);
        }

        removeIfExists(beanName);
        if (checkCandidate(beanName, candidate)) {

            BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(candidate, beanName);
            definitionHolder = applyScopedProxyMode(scopeMetadata, definitionHolder, registry);

            LOGGER.reload("Registering Spring bean '{}'", beanName);
            LOGGER.debug("Bean definition '{}'", beanName, candidate);
            registerBeanDefinition(definitionHolder, registry);

            DefaultListableBeanFactory bf = maybeRegistryToBeanFactory();
            if (bf != null)
                ResetRequestMappingCaches.reset(bf);

            ProxyReplacer.clearAllProxies();
            freezeConfiguration();
        }
    }


}
 
Example 17
/**
 * Prepare the script beans in the internal BeanFactory that this
 * post-processor uses. Each original bean definition will be split
 * into a ScriptFactory definition and a scripted object definition.
 * @param bd the original bean definition in the main BeanFactory
 * @param scriptFactoryBeanName the name of the internal ScriptFactory bean
 * @param scriptedObjectBeanName the name of the internal scripted object bean
 */
protected void prepareScriptBeans(BeanDefinition bd, String scriptFactoryBeanName, String scriptedObjectBeanName) {
	// Avoid recreation of the script bean definition in case of a prototype.
	synchronized (this.scriptBeanFactory) {
		if (!this.scriptBeanFactory.containsBeanDefinition(scriptedObjectBeanName)) {

			this.scriptBeanFactory.registerBeanDefinition(
					scriptFactoryBeanName, createScriptFactoryBeanDefinition(bd));
			ScriptFactory scriptFactory =
					this.scriptBeanFactory.getBean(scriptFactoryBeanName, ScriptFactory.class);
			ScriptSource scriptSource =
					getScriptSource(scriptFactoryBeanName, scriptFactory.getScriptSourceLocator());
			Class<?>[] interfaces = scriptFactory.getScriptInterfaces();

			Class<?>[] scriptedInterfaces = interfaces;
			if (scriptFactory.requiresConfigInterface() && !bd.getPropertyValues().isEmpty()) {
				Class<?> configInterface = createConfigInterface(bd, interfaces);
				scriptedInterfaces = ObjectUtils.addObjectToArray(interfaces, configInterface);
			}

			BeanDefinition objectBd = createScriptedObjectBeanDefinition(
					bd, scriptFactoryBeanName, scriptSource, scriptedInterfaces);
			long refreshCheckDelay = resolveRefreshCheckDelay(bd);
			if (refreshCheckDelay >= 0) {
				objectBd.setScope(BeanDefinition.SCOPE_PROTOTYPE);
			}

			this.scriptBeanFactory.registerBeanDefinition(scriptedObjectBeanName, objectBd);
		}
	}
}
 
Example 18
public static <T> void registerBeanDefinition(Class<T> clazz, String scope) {
    BeanDefinition definition = new GenericBeanDefinition();
    definition.setScope(scope);
    definition.setBeanClassName(clazz.getName());
    Lock wlock = rwLock.writeLock();
    wlock.lock();
    try {
        ((DefaultListableBeanFactory) beanFactory).registerBeanDefinition(clazz.getName(), definition);
        // TODO : Has to register beans twice to flush cache, might be a Spring defect. Workaround.
        ((DefaultListableBeanFactory) beanFactory).registerBeanDefinition(clazz.getName(), definition);
    } finally {
        wlock.unlock();
    }
}
 
Example 19
protected void emitCustomStoreBeanDefinition(final BeanDefinitionRegistry registry, final String storeName)
{
    if (registry.containsBeanDefinition(storeName))
    {
        throw new AlfrescoRuntimeException(
                storeName + " (custom content store) cannot be defined - a bean with same name already exists");
    }

    final MessageFormat mf = new MessageFormat("{0}.{1}.", Locale.ENGLISH);
    final String prefix = mf.format(new Object[] { PROP_CUSTOM_STORE_PREFIX, storeName });
    final String typeProperty = prefix + "type";
    final String typeValue = this.propertiesSource.getProperty(typeProperty);

    if (typeValue != null && !typeValue.isEmpty())
    {
        LOGGER.debug("Emitting bean definition for custom store {} based on template {}", storeName, typeValue);
        final BeanDefinition storeBeanDefinition = new ChildBeanDefinition(STORE_TEMPLATE_PREFIX + typeValue);
        storeBeanDefinition.setScope(BeanDefinition.SCOPE_SINGLETON);

        final Set<String> propertyNames = this.propertiesSource.stringPropertyNames();
        for (final String propertyName : propertyNames)
        {
            if (propertyName.startsWith(prefix) && !typeProperty.equals(propertyName))
            {
                this.handleBeanProperty(storeBeanDefinition, propertyName, this.propertiesSource.getProperty(propertyName));
            }
        }

        registry.registerBeanDefinition(storeName, storeBeanDefinition);
    }
    else
    {
        LOGGER.warn("Custom store {} does not define a type", storeName);
        throw new AlfrescoRuntimeException(storeName + " (custom content store) has not been given a type");
    }
}
 
Example 20
Source Project: mdw   File: AnnotationsScanner.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Source files under src/main/java are scanned for @Activity annotations.
 */
public void findSpringAnnotatedClasses() {
    List<String> scanPackages = AutoConfigurationPackages.get(beanFactory);
    ClassPathScanningCandidateComponentProvider provider = createScannerComponentProvider();
    for (String scanPackage : scanPackages) {
        for (BeanDefinition beanDef : provider.findCandidateComponents(scanPackage)) {
            beanDef.setScope(BeanDefinition.SCOPE_PROTOTYPE);
            addImplementor(beanDef);
        }
    }
}