org.springframework.beans.factory.config.BeanDefinition#setScope ( )源码实例Demo

下面列出了org.springframework.beans.factory.config.BeanDefinition#setScope ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: TrackRay   文件: ModuleClassLoader.java
/**
 * 方法描述 初始化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);
        }
    }
}
 
@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());
		}
	}
}
 
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;
}
 
/**
 * 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;
}
 
/**
 * 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());
		}
	}
}
 
/**
 * 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);
		}
	}
}
 
/**
 * 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;
}
 
/**
 * 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);
		}
	}
}
 
/**
 * 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;
}
 
源代码10 项目: pacbot   文件: RefreshScopeConfig.java
@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");
        }
    }
}
 
源代码11 项目: pacbot   文件: RefreshScopeConfig.java
/**
 * 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");
        }
    }
}
 
源代码12 项目: pacbot   文件: RefreshScopeConfig.java
@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");
		}
	}
}
 
源代码13 项目: pacbot   文件: RefreshScopeConfig.java
@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");
		}
	}
}
 
源代码14 项目: pacbot   文件: RefreshScopeConfig.java
@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");
        }
    }
}
 
源代码15 项目: happor   文件: HapporSpringContext.java
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);
}
 
/**
 * 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();
        }
    }


}
 
/**
 * 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);
		}
	}
}
 
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();
    }
}
 
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");
    }
}
 
源代码20 项目: mdw   文件: AnnotationsScanner.java
/**
 * 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);
        }
    }
}