List of usage examples for org.springframework.beans.factory.support AbstractBeanDefinition setScope
@Override public void setScope(@Nullable String scope)
From source file:com.griddynamics.banshun.xml.ImportBeanDefinitionParser.java
@Override protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) { String exportInterface = element.getAttribute(INTERFACE_ATTR); if (isBlank(exportInterface)) { return;//from www . j a va 2 s. co m } String externalName = element.getAttribute(ID_ATTR); if (isBlank(externalName)) { return; } String rootName = element.getAttribute(ROOT_ATTR); if (isBlank(rootName)) { rootName = DEFAULT_ROOT_FACTORY_NAME; } ConstructorArgumentValues constructorArgValues = new ConstructorArgumentValues(); constructorArgValues.addGenericArgumentValue(externalName); constructorArgValues.addGenericArgumentValue(findClass(exportInterface, element.getAttribute(ID_ATTR), parserContext.getReaderContext().getResource().getDescription())); AbstractBeanDefinition beanDef = builder.getRawBeanDefinition(); beanDef.setFactoryBeanName(rootName); beanDef.setFactoryMethodName("lookup"); beanDef.setConstructorArgumentValues(constructorArgValues); beanDef.setLazyInit(true); beanDef.setScope(SCOPE_SINGLETON); }
From source file:com.griddynamics.banshun.xml.ExportBeanDefinitionParser.java
@Override protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) { BeanDefinitionRegistry registry = parserContext.getRegistry(); String exportInterface = element.getAttribute(INTERFACE_ATTR); if (isBlank(exportInterface)) { return;//from ww w. j a va 2 s . c om } String exportBeanRef = element.getAttribute(REF_ATTR); if (isBlank(exportBeanRef)) { return; } String rootName = element.getAttribute(ROOT_ATTR); if (isBlank(rootName)) { rootName = DEFAULT_ROOT_FACTORY_NAME; } String exportName = element.getAttribute(NAME_ATTR); if (isBlank(exportName)) { exportName = exportBeanRef; } String exportRefName = exportName + BEAN_NAME_SUFFIX; if (registry.containsBeanDefinition(exportRefName)) { throw new BeanCreationException("Registry already contains bean with name: " + exportRefName); } ConstructorArgumentValues exportBeanConstructorArgValues = new ConstructorArgumentValues(); exportBeanConstructorArgValues.addGenericArgumentValue(exportName); exportBeanConstructorArgValues.addGenericArgumentValue(findClass(exportInterface, exportBeanRef, parserContext.getReaderContext().getResource().getDescription())); AbstractBeanDefinition exportBeanDef = rootBeanDefinition(ExportRef.class).getRawBeanDefinition(); exportBeanDef.setConstructorArgumentValues(exportBeanConstructorArgValues); ConstructorArgumentValues voidBeanConstructorArgValues = new ConstructorArgumentValues(); voidBeanConstructorArgValues.addGenericArgumentValue(exportBeanDef, ExportRef.class.getName()); AbstractBeanDefinition voidBeanDef = rootBeanDefinition(Void.class).getRawBeanDefinition(); voidBeanDef.setFactoryBeanName(rootName); voidBeanDef.setFactoryMethodName("export"); voidBeanDef.setLazyInit(false); voidBeanDef.setScope(SCOPE_SINGLETON); voidBeanDef.setConstructorArgumentValues(voidBeanConstructorArgValues); // voidBeanDefinition.setDependsOn(new String[] { exportBeanRef }); TODO ? registry.registerBeanDefinition(exportRefName, voidBeanDef); }
From source file:com.griddynamics.banshun.config.xml.ImportBeanDefinitionParser.java
@Override protected void doParse(Element el, ParserContext parserContext, BeanDefinitionBuilder builder) { Resource resource = parserContext.getReaderContext().getResource(); String rootName = defaultIfBlank(el.getAttribute(ROOT_ATTR), DEFAULT_ROOT_FACTORY_NAME); String serviceIfaceName = el.getAttribute(INTERFACE_ATTR); String serviceName = el.getAttribute(ID_ATTR); Class<?> serviceIface = ParserUtils.findClassByName(serviceIfaceName, el.getAttribute(ID_ATTR), parserContext);//from w w w. jav a2s .c om AbstractBeanDefinition beanDef = builder.getRawBeanDefinition(); beanDef.setFactoryBeanName(rootName); beanDef.setFactoryMethodName(Registry.LOOKUP_METHOD_NAME); beanDef.setConstructorArgumentValues(defineLookupMethodArgs(serviceName, serviceIface)); beanDef.setLazyInit(true); beanDef.setScope(SCOPE_SINGLETON); beanDef.setResource(resource); beanDef.setAttribute(IMPORT_BEAN_DEF_ATTR_NAME, new BeanReferenceInfo(serviceName, serviceIface, extractResourcePath(resource))); }
From source file:de.acosix.alfresco.mtsupport.repo.beans.TemplatedTenantBeanEmitter.java
/** * {@inheritDoc}//from w w w . j ava2 s . c o m */ @Override public void postProcessBeanDefinitionRegistry(final BeanDefinitionRegistry registry) throws BeansException { if (this.isEnabled()) { final String enabledTenantsProperty = this.effectiveProperties .getProperty(this.enabledTenantPropertyKey); if (enabledTenantsProperty == null || enabledTenantsProperty.trim().isEmpty()) { LOGGER.debug("No tenants have been defined as enabled"); } else { final List<String> enabledTenants = Arrays.asList(enabledTenantsProperty.trim().split("\\s*,\\s*")); LOGGER.debug("Processing beans {} for enabled tenants {}", this.beanNames, enabledTenants); for (final String beanName : this.beanNames) { LOGGER.debug("Processing {}", beanName); final String templateBeanName = beanName + TenantBeanUtils.TENANT_BEAN_TEMPLATE_SUFFIX; if (registry.containsBeanDefinition(templateBeanName)) { final BeanDefinition beanDefinition = registry.getBeanDefinition(templateBeanName); if (beanDefinition instanceof AbstractBeanDefinition) { for (final String tenant : enabledTenants) { final AbstractBeanDefinition cloneBeanDefinition = ((AbstractBeanDefinition) beanDefinition) .cloneBeanDefinition(); cloneBeanDefinition.setScope(AbstractBeanDefinition.SCOPE_DEFAULT); this.shallowCloneManagedCollections(cloneBeanDefinition); final String tenantBeanName = beanName + TenantBeanUtils.TENANT_BEAN_NAME_PATTERN + tenant; LOGGER.debug("Adding clone of {} for tenant {}", templateBeanName, tenant); registry.registerBeanDefinition(tenantBeanName, cloneBeanDefinition); } } } else { LOGGER.warn("No template bean defined for {}", beanName); } } } } }
From source file:de.codecentric.batch.jsr352.CustomJsrJobOperator.java
@Override public long start(String jobName, Properties params) throws JobStartException, JobSecurityException { final JsrXmlApplicationContext batchContext = new JsrXmlApplicationContext(params); batchContext.setValidating(false);//from w w w . j a v a 2 s.c o m Resource batchXml = new ClassPathResource("/META-INF/batch.xml"); String jobConfigurationLocation = "/META-INF/batch-jobs/" + jobName + ".xml"; Resource jobXml = new ClassPathResource(jobConfigurationLocation); if (batchXml.exists()) { batchContext.load(batchXml); } if (jobXml.exists()) { batchContext.load(jobXml); } AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder .genericBeanDefinition("org.springframework.batch.core.jsr.JsrJobContextFactoryBean") .getBeanDefinition(); beanDefinition.setScope(BeanDefinition.SCOPE_SINGLETON); batchContext.registerBeanDefinition(JSR_JOB_CONTEXT_BEAN_NAME, beanDefinition); batchContext.setParent(parentContext); try { batchContext.refresh(); } catch (BeanCreationException e) { throw new JobStartException(e); } Assert.notNull(jobName, "The job name must not be null."); final org.springframework.batch.core.JobExecution jobExecution; try { JobParameters jobParameters = jobParametersConverter.getJobParameters(params); String[] jobNames = batchContext.getBeanNamesForType(Job.class); if (jobNames == null || jobNames.length <= 0) { throw new BatchRuntimeException("No Job defined in current context"); } org.springframework.batch.core.JobInstance jobInstance = jobRepository.createJobInstance(jobNames[0], jobParameters); jobExecution = jobRepository.createJobExecution(jobInstance, jobParameters, jobConfigurationLocation); } catch (Exception e) { throw new JobStartException(e); } try { final Semaphore semaphore = new Semaphore(1); final List<Exception> exceptionHolder = Collections.synchronizedList(new ArrayList<Exception>()); semaphore.acquire(); taskExecutor.execute(new Runnable() { @Override public void run() { JsrJobContextFactoryBean factoryBean = null; try { factoryBean = (JsrJobContextFactoryBean) batchContext .getBean("&" + JSR_JOB_CONTEXT_BEAN_NAME); factoryBean.setJobExecution(jobExecution); final AbstractJob job = batchContext.getBean(AbstractJob.class); addListenerToJobService.addListenerToJob(job); semaphore.release(); // Initialization of the JobExecution for job level dependencies jobRegistry.register(job, jobExecution); job.execute(jobExecution); jobRegistry.remove(jobExecution); } catch (Exception e) { exceptionHolder.add(e); } finally { if (factoryBean != null) { factoryBean.close(); } batchContext.close(); if (semaphore.availablePermits() == 0) { semaphore.release(); } } } }); semaphore.acquire(); if (exceptionHolder.size() > 0) { semaphore.release(); throw new JobStartException(exceptionHolder.get(0)); } } catch (Exception e) { if (jobRegistry.exists(jobExecution.getId())) { jobRegistry.remove(jobExecution); } jobExecution.upgradeStatus(BatchStatus.FAILED); if (jobExecution.getExitStatus().equals(ExitStatus.UNKNOWN)) { jobExecution.setExitStatus(ExitStatus.FAILED.addExitDescription(e)); } jobRepository.update(jobExecution); if (batchContext.isActive()) { batchContext.close(); } throw new JobStartException(e); } return jobExecution.getId(); }
From source file:org.os890.ds.addon.spring.impl.CdiAwareBeanFactoryPostProcessor.java
private BeanDefinition createSpringBeanDefinition(Bean<?> cdiBean) throws Exception { AbstractBeanDefinition beanDefinition = new GenericBeanDefinition(); Set<Type> beanTypes = new HashSet<Type>(cdiBean.getTypes()); beanTypes.remove(Object.class); beanTypes.remove(Serializable.class); Type beanType = beanTypes.size() == 1 ? beanTypes.iterator().next() : null; if (beanType instanceof Class) { //to support producers beanDefinition.setBeanClass((Class) beanType); } else { //fallback since spring doesn't support multiple types beanDefinition.setBeanClass(cdiBean.getBeanClass()); }/*w ww . java 2 s . c o m*/ beanDefinition.setScope(CdiSpringScope.class.getName()); for (Annotation qualifier : cdiBean.getQualifiers()) { if (Any.class.equals(qualifier.annotationType()) || Default.class.equals(qualifier.annotationType())) { continue; } //currently only simple qualifiers are supported AutowireCandidateQualifier springQualifier = new AutowireCandidateQualifier(qualifier.annotationType()); for (Method annotationMethod : qualifier.annotationType().getDeclaredMethods()) { if (!annotationMethod.isAnnotationPresent(Nonbinding.class)) { springQualifier.setAttribute(annotationMethod.getName(), annotationMethod.invoke(qualifier)); } } beanDefinition.addQualifier(springQualifier); } beanDefinition.setLazyInit(true); return beanDefinition; }
From source file:com.seovic.validation.config.ValidationBeanDefinitionParser.java
@SuppressWarnings("unchecked") private BeanDefinition parseValidator(Element element, ParserContext parserContext) { String parent = element.getAttribute("parent"); if ("".equals(parent)) { parent = null;//from w ww . j a va 2 s .c o m } String test = element.getAttribute("test"); String when = element.getAttribute("when"); String validateAll = element.getAttribute("validate-all"); String context = element.getAttribute("context"); String includeElementsErrors = element.getAttribute("include-element-errors"); MutablePropertyValues properties = new MutablePropertyValues(); if (StringUtils.hasText(test)) { properties.addPropertyValue("test", test); } if (StringUtils.hasText(when)) { properties.addPropertyValue("when", when); } if (StringUtils.hasText(validateAll)) { properties.addPropertyValue("validateAll", validateAll); } if (StringUtils.hasText(context)) { properties.addPropertyValue("context", context); } if (StringUtils.hasText(includeElementsErrors)) { properties.addPropertyValue("includeElementsErrors", includeElementsErrors); } ManagedList nestedValidators = new ManagedList(); ManagedList actions = new ManagedList(); for (int i = 0; i < element.getChildNodes().getLength(); i++) { Node child = element.getChildNodes().item(i); if (child != null && child instanceof Element) { Element childElement = (Element) child; if ("message".equals(childElement.getLocalName())) { actions.add(parseErrorMessageAction(childElement, parserContext)); } else { nestedValidators.add(parseAndRegisterValidator2(childElement, parserContext)); } } } if (nestedValidators.size() > 0) { properties.addPropertyValue("validators", nestedValidators); } if (actions.size() > 0) { properties.addPropertyValue("actions", actions); } String className; if ("required".equals(element.getLocalName())) { className = RequiredValidator.class.getName(); } else if ("condition".equals(element.getLocalName())) { className = ConditionValidator.class.getName(); } else if ("validator".equals(element.getLocalName())) { className = element.getAttribute("type"); } else { className = ValidatorGroup.class.getName(); } AbstractBeanDefinition validatorDefinition; try { validatorDefinition = BeanDefinitionReaderUtils.createBeanDefinition(parent, className, parserContext.getReaderContext().getBeanClassLoader()); } catch (ClassNotFoundException e) { throw new BeanCreationException("Error occured during creation of bean definition", e); } validatorDefinition.setResource(parserContext.getReaderContext().getResource()); validatorDefinition.setSource(parserContext.extractSource(element)); validatorDefinition.setPropertyValues(properties); validatorDefinition.setLazyInit(true); validatorDefinition.setScope("singleton"); return validatorDefinition; }
From source file:org.eclipse.gemini.blueprint.blueprint.config.internal.BlueprintParser.java
/** * Parse the bean definition itself, without regard to name or aliases. May return <code>null</code> if problems * occurred during the parse of the bean definition. */// w w w. j a va 2 s. co m private AbstractBeanDefinition parseBeanDefinitionElement(Element ele, String beanName, BeanDefinition containingBean) { this.parseState.push(new BeanEntry(beanName)); String className = null; if (ele.hasAttribute(BeanDefinitionParserDelegate.CLASS_ATTRIBUTE)) { className = ele.getAttribute(BeanDefinitionParserDelegate.CLASS_ATTRIBUTE).trim(); } try { AbstractBeanDefinition beanDefinition = BeanDefinitionReaderUtils.createBeanDefinition(null, className, parserContext.getReaderContext().getBeanClassLoader()); // some early validation String activation = ele.getAttribute(LAZY_INIT_ATTR); String scope = ele.getAttribute(BeanDefinitionParserDelegate.SCOPE_ATTRIBUTE); if (EAGER_INIT_VALUE.equals(activation) && BeanDefinition.SCOPE_PROTOTYPE.equals(scope)) { error("Prototype beans cannot be eagerly activated", ele); } // add marker to indicate that the scope was present if (StringUtils.hasText(scope)) { beanDefinition.setAttribute(DECLARED_SCOPE, Boolean.TRUE); } // parse attributes parseAttributes(ele, beanName, beanDefinition); // inner beans get a predefined scope in RFC 124 if (containingBean != null) { beanDefinition.setLazyInit(true); beanDefinition.setScope(BeanDefinition.SCOPE_PROTOTYPE); } // parse description beanDefinition.setDescription( DomUtils.getChildElementValueByTagName(ele, BeanDefinitionParserDelegate.DESCRIPTION_ELEMENT)); parseConstructorArgElements(ele, beanDefinition); parsePropertyElements(ele, beanDefinition); beanDefinition.setResource(parserContext.getReaderContext().getResource()); beanDefinition.setSource(extractSource(ele)); return beanDefinition; } catch (ClassNotFoundException ex) { error("Bean class [" + className + "] not found", ele, ex); } catch (NoClassDefFoundError err) { error("Class that bean class [" + className + "] depends on not found", ele, err); } catch (Throwable ex) { error("Unexpected failure during bean definition parsing", ele, ex); } finally { this.parseState.pop(); } return null; }
From source file:org.springframework.batch.core.jsr.configuration.xml.BatchParser.java
private void parseRefElements(Element element, BeanDefinitionRegistry registry) { List<Element> beanElements = DomUtils.getChildElementsByTagName(element, "ref"); if (beanElements.size() > 0) { for (Element curElement : beanElements) { AbstractBeanDefinition beanDefintion = BeanDefinitionBuilder .genericBeanDefinition(curElement.getAttribute("class")).getBeanDefinition(); beanDefintion.setScope("step"); String beanName = curElement.getAttribute("id"); if (!registry.containsBeanDefinition(beanName)) { registry.registerBeanDefinition(beanName, beanDefintion); } else { logger.info("Ignoring batch.xml bean defintion for " + beanName + " because another bean of the same name has been registered"); }//ww w. j a v a 2 s . c o m } } }
From source file:org.springframework.batch.core.jsr.configuration.xml.JsrBeanDefinitionDocumentReader.java
private void transformDocument(Element root) { DocumentTraversal traversal = (DocumentTraversal) root.getOwnerDocument(); NodeIterator iterator = traversal.createNodeIterator(root, NodeFilter.SHOW_ELEMENT, null, true); BeanDefinitionRegistry registry = getBeanDefinitionRegistry(); Map<String, Integer> referenceCountMap = new HashMap<String, Integer>(); for (Node n = iterator.nextNode(); n != null; n = iterator.nextNode()) { NamedNodeMap map = n.getAttributes(); if (map.getLength() > 0) { for (int i = 0; i < map.getLength(); i++) { Node node = map.item(i); String nodeName = node.getNodeName(); String nodeValue = node.getNodeValue(); String resolvedValue = resolveValue(nodeValue); String newNodeValue = resolvedValue; if ("ref".equals(nodeName)) { if (!referenceCountMap.containsKey(resolvedValue)) { referenceCountMap.put(resolvedValue, 0); }/*from w w w .j a v a 2 s. co m*/ boolean isClass = isClass(resolvedValue); Integer referenceCount = referenceCountMap.get(resolvedValue); // possibly fully qualified class name in ref tag in the JSL or pointer to bean/artifact ref. if (isClass && !registry.containsBeanDefinition(resolvedValue)) { AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder .genericBeanDefinition(resolvedValue).getBeanDefinition(); beanDefinition.setScope("step"); registry.registerBeanDefinition(resolvedValue, beanDefinition); newNodeValue = resolvedValue; } else { if (registry.containsBeanDefinition(resolvedValue)) { referenceCount++; referenceCountMap.put(resolvedValue, referenceCount); newNodeValue = resolvedValue + referenceCount; BeanDefinition beanDefinition = registry.getBeanDefinition(resolvedValue); registry.registerBeanDefinition(newNodeValue, beanDefinition); } } } if (!nodeValue.equals(newNodeValue)) { node.setNodeValue(newNodeValue); } } } else { String nodeValue = n.getTextContent(); String resolvedValue = resolveValue(nodeValue); if (!nodeValue.equals(resolvedValue)) { n.setTextContent(resolvedValue); } } } }