List of usage examples for org.springframework.beans.factory.config BeanDefinition setAttribute
void setAttribute(String name, @Nullable Object value);
From source file:com.mtgi.analytics.aop.config.TemplateBeanDefinitionParser.java
/** * Convenience method to update a template bean definition from overriding XML data. * If <code>overrides</code> contains attribute <code>attribute</code>, transfer that * attribute onto <code>template</code>, overwriting the default value. *//* w w w . j a va 2 s. co m*/ public static String overrideAttribute(String attribute, BeanDefinition template, Element overrides) { String value = (String) template.getAttribute(attribute); if (overrides.hasAttribute(attribute)) { value = overrides.getAttribute(attribute); template.setAttribute(attribute, value); } return value; }
From source file:org.jdal.aop.SerializableProxyUtils.java
public static BeanDefinitionHolder createSerializableProxy(BeanDefinitionHolder definition, BeanDefinitionRegistry registry, boolean proxyTargetClass) { String originalBeanName = definition.getBeanName(); BeanDefinition targetDefinition = definition.getBeanDefinition(); // Create a scoped proxy definition for the original bean name, // "hiding" the target bean in an internal target definition. RootBeanDefinition proxyDefinition = new RootBeanDefinition(SerializableProxyFactoryBean.class); proxyDefinition.setOriginatingBeanDefinition(definition.getBeanDefinition()); proxyDefinition.setSource(definition.getSource()); proxyDefinition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); String targetBeanName = getTargetBeanName(originalBeanName); proxyDefinition.getPropertyValues().add("targetBeanName", targetBeanName); if (proxyTargetClass) { targetDefinition.setAttribute(AutoProxyUtils.PRESERVE_TARGET_CLASS_ATTRIBUTE, Boolean.TRUE); } else {/*from w w w . j av a 2s. co m*/ proxyDefinition.getPropertyValues().add("proxyTargetClass", Boolean.FALSE); } // Copy autowire settings from original bean definition. proxyDefinition.setAutowireCandidate(targetDefinition.isAutowireCandidate()); proxyDefinition.setPrimary(targetDefinition.isPrimary()); if (targetDefinition instanceof AbstractBeanDefinition) { proxyDefinition.copyQualifiersFrom((AbstractBeanDefinition) targetDefinition); } // Set singleton property of FactoryBean proxyDefinition.getPropertyValues().add("singleton", !targetDefinition.isPrototype()); // The target bean should be ignored in favor of the scoped proxy. targetDefinition.setAutowireCandidate(false); targetDefinition.setPrimary(false); // Register the target bean as separate bean in the factory. registry.registerBeanDefinition(targetBeanName, targetDefinition); // Return the scoped proxy definition as primary bean definition // (potentially an inner bean). return new BeanDefinitionHolder(proxyDefinition, originalBeanName, definition.getAliases()); }
From source file:com.helpinput.spring.BeanRegister.java
public static BeanDefinitionWrap registerBean(ApplicationContext context, DefaultListableBeanFactory dlbf, BeanDefinitionBuilder builder, Class<?> clz, String beanName, String scope, BeanInfo beanInfo) { if (!Utils.hasLength(beanName)) { beanName = Commons.getBeanName(clz); if (!Utils.hasLength(beanName)) beanName = Utils.beanName(beanInfo.scanName); }/*from w w w. j a v a 2 s . c o m*/ if (!Utils.hasLength(beanName)) return null; //bean?bean if (beanName.endsWith("Impl")) { beanName = beanName.substring(0, beanName.length() - 4); } if (!Utils.hasLength(beanName)) return null; removeBean(dlbf, beanInfo, null); BeanDefinition bd = null; if (!Utils.hasLength(scope)) scope = findScopeStr(clz); List<BeanRegistInterceptor> interceptors = ContextHolder.beanRegistIntercpterHolder.getList(); if (Utils.hasLength(interceptors)) { for (BeanRegistInterceptor beanRegistInterceptor : interceptors) { bd = beanRegistInterceptor.beforeRegist(clz, beanName, scope, dlbf, builder); if (bd != null) break; } } if (bd == null) bd = builder.getBeanDefinition(); if (beanInfo != null) bd.setAttribute(relativePath, beanInfo.relativePath); bd.setScope(scope); dlbf.registerBeanDefinition(beanName, bd); boolean isUpdate = beanInfo != null ? beanInfo.isUpdate : false; String relativePath = beanInfo != null ? beanInfo.relativePath : ""; BeanDefinitionWrap beanDefinitionWrap = new BeanDefinitionWrap(beanName, bd); if (ContextRefresher.class.isAssignableFrom(clz)) { ContextHolder.refreshers.register(beanName); } logRegist(isUpdate ? Info.Updated : Info.Registed, relativePath, beanName, scope); return beanDefinitionWrap; }
From source file:org.mule.transport.zmq.config.InboundEndpointDefinitionParser.java
public BeanDefinition parseChild(Element element, ParserContext parserContent) { BeanDefinitionBuilder builder = BeanDefinitionBuilder .rootBeanDefinition(InboundEndpointMessageSource.class.getName()); String configRef = element.getAttribute("config-ref"); if ((configRef != null) && (!StringUtils.isBlank(configRef))) { builder.addPropertyValue("moduleObject", configRef); }/*from ww w.j a v a2s . c o m*/ if (element.hasAttribute("exchange-pattern")) { builder.addPropertyValue("exchangePattern", element.getAttribute("exchange-pattern")); } if (element.hasAttribute("socket-operation")) { builder.addPropertyValue("socketOperation", element.getAttribute("socket-operation")); } if ((element.getAttribute("address") != null) && (!StringUtils.isBlank(element.getAttribute("address")))) { builder.addPropertyValue("address", element.getAttribute("address")); } if ((element.getAttribute("filter") != null) && (!StringUtils.isBlank(element.getAttribute("filter")))) { builder.addPropertyValue("filter", element.getAttribute("filter")); } if ((element.getAttribute("identity") != null) && (!StringUtils.isBlank(element.getAttribute("identity")))) { builder.addPropertyValue("identity", element.getAttribute("identity")); } if ((element.getAttribute("multipart") != null) && (!StringUtils.isBlank(element.getAttribute("multipart")))) { builder.addPropertyValue("multipart", element.getAttribute("multipart")); } if ((element.getAttribute("retryMax") != null) && (!StringUtils.isBlank(element.getAttribute("retryMax")))) { builder.addPropertyValue("retryMax", element.getAttribute("retryMax")); } BeanDefinition definition = builder.getBeanDefinition(); definition.setAttribute(MuleHierarchicalBeanDefinitionParserDelegate.MULE_NO_RECURSE, Boolean.TRUE); MutablePropertyValues propertyValues = parserContent.getContainingBeanDefinition().getPropertyValues(); propertyValues.addPropertyValue("messageSource", definition); return definition; }
From source file:org.mule.transport.zmq.config.OutboundEndpointDefinitionParser.java
public BeanDefinition parse(Element element, ParserContext parserContent) { BeanDefinitionBuilder builder = BeanDefinitionBuilder .rootBeanDefinition(OutboundEndpointMessageProcessor.class.getName()); String configRef = element.getAttribute("config-ref"); if ((configRef != null) && (!StringUtils.isBlank(configRef))) { builder.addPropertyValue("moduleObject", configRef); }//from w w w . ja v a 2 s.c o m if ((element.getAttribute("payload-ref") != null) && (!StringUtils.isBlank(element.getAttribute("payload-ref")))) { if (element.getAttribute("payload-ref").startsWith("#")) { builder.addPropertyValue("payload", element.getAttribute("payload-ref")); } else { builder.addPropertyValue("payload", (("#[registry:" + element.getAttribute("payload-ref")) + "]")); } } if ((element.getAttribute("retryMax") != null) && (!StringUtils.isBlank(element.getAttribute("retryMax")))) { builder.addPropertyValue("retryMax", element.getAttribute("retryMax")); } if (element.hasAttribute("exchange-pattern")) { builder.addPropertyValue("exchangePattern", element.getAttribute("exchange-pattern")); } if (element.hasAttribute("socket-operation")) { builder.addPropertyValue("socketOperation", element.getAttribute("socket-operation")); } if ((element.getAttribute("address") != null) && (!StringUtils.isBlank(element.getAttribute("address")))) { builder.addPropertyValue("address", element.getAttribute("address")); } if ((element.getAttribute("filter") != null) && (!StringUtils.isBlank(element.getAttribute("filter")))) { builder.addPropertyValue("filter", element.getAttribute("filter")); } if ((element.getAttribute("identity") != null) && (!StringUtils.isBlank(element.getAttribute("identity")))) { builder.addPropertyValue("identity", element.getAttribute("identity")); } if ((element.getAttribute("multipart") != null) && (!StringUtils.isBlank(element.getAttribute("multipart")))) { builder.addPropertyValue("multipart", element.getAttribute("multipart")); } BeanDefinition definition = builder.getBeanDefinition(); definition.setAttribute(MuleHierarchicalBeanDefinitionParserDelegate.MULE_NO_RECURSE, Boolean.TRUE); MutablePropertyValues propertyValues = parserContent.getContainingBeanDefinition().getPropertyValues(); if (parserContent.getContainingBeanDefinition().getBeanClassName() .equals("org.mule.config.spring.factories.PollingMessageSourceFactoryBean")) { propertyValues.addPropertyValue("messageProcessor", definition); } else { if (parserContent.getContainingBeanDefinition().getBeanClassName() .equals("org.mule.enricher.MessageEnricher")) { propertyValues.addPropertyValue("enrichmentMessageProcessor", definition); } else { PropertyValue messageProcessors = propertyValues.getPropertyValue("messageProcessors"); if ((messageProcessors == null) || (messageProcessors.getValue() == null)) { propertyValues.addPropertyValue("messageProcessors", new ManagedList()); } List listMessageProcessors = ((List) propertyValues.getPropertyValue("messageProcessors") .getValue()); listMessageProcessors.add(definition); } } return definition; }
From source file:com.griddynamics.banshun.config.xml.ExportBeanDefinitionParser.java
@Override protected void doParse(Element el, ParserContext parserContext, BeanDefinitionBuilder builder) { BeanDefinitionRegistry registry = parserContext.getRegistry(); Resource resource = parserContext.getReaderContext().getResource(); String rootName = defaultIfBlank(el.getAttribute(ROOT_ATTR), DEFAULT_ROOT_FACTORY_NAME); String serviceIfaceName = el.getAttribute(INTERFACE_ATTR); String beanName = el.getAttribute(REF_ATTR); String serviceName = defaultIfBlank(el.getAttribute(NAME_ATTR), beanName); String exportBeanDefName = serviceName + EXPORT_REF_SUFFIX; if (registry.containsBeanDefinition(exportBeanDefName)) { throw new BeanCreationException("Registry already contains bean with name: " + exportBeanDefName); }// w ww.ja va2s . co m Class<?> serviceIface = ParserUtils.findClassByName(serviceIfaceName, beanName, parserContext); BeanDefinition exportRefBeanDef = defineExportRef(serviceName, serviceIface, beanName); BeanDefinition exportFactoryBeanDef = defineExportFactoryBean(rootName, exportRefBeanDef, resource); exportFactoryBeanDef.setAttribute(EXPORT_BEAN_DEF_ATTR_NAME, new BeanReferenceInfo(serviceName, serviceIface, extractResourcePath(resource))); registry.registerBeanDefinition(exportBeanDefName, exportFactoryBeanDef); }
From source file:org.constretto.spring.EnvironmentAnnotationConfigurer.java
@SuppressWarnings("unchecked") private void removeNonAnnotatedBeansFromAutowireForType(Class lookupClass, ConfigurableListableBeanFactory configurableListableBeanFactory) throws ClassNotFoundException { List<String> beanNames = new ArrayList<String>(); Class[] interfaces = lookupClass.getInterfaces(); for (Class anInterface : interfaces) { beanNames.addAll(asList(BeanFactoryUtils .beanNamesForTypeIncludingAncestors(configurableListableBeanFactory, anInterface))); }/*w w w . j a va2s . c o m*/ List<BeanDefinition> potentialMatches = new ArrayList<BeanDefinition>(); for (String beanName : beanNames) { BeanDefinition beanDefinition = configurableListableBeanFactory.getBeanDefinition(beanName); Class beanClass = Class.forName(beanDefinition.getBeanClassName()); beanDefinition.setAttribute(INCLUDE_IN_COLLECTIONS, beanClass.getInterfaces()); Environment environmentAnnotation = findEnvironmentAnnotation(beanClass); if (environmentAnnotation == null) { beanDefinition.setAutowireCandidate(false); } else { potentialMatches.add(beanDefinition); } } if (potentialMatches.size() == 1) { potentialMatches.get(0).setAutowireCandidate(true); } else { List<BeanDefinition> highestPriorityBeans = new ArrayList<BeanDefinition>(); for (BeanDefinition potentialMatch : potentialMatches) { if (potentialMatch.isAutowireCandidate()) { potentialMatch.setAutowireCandidate(false); highestPriorityBeans = prioritizeBeans(potentialMatch, highestPriorityBeans); } } if (highestPriorityBeans.size() == 1) { highestPriorityBeans.get(0).setAutowireCandidate(true); } else { List<String> equalPriorityBeans = new ArrayList<String>(); for (BeanDefinition highestPriorityBean : highestPriorityBeans) { equalPriorityBeans.add(highestPriorityBean.getBeanClassName()); } throw new ConstrettoException("More than one bean with the class or interface + [" + lookupClass.getSimpleName() + "] registered with same tag. Could not resolve priority. To fix this, remove one of the following beans " + equalPriorityBeans.toString()); } } }
From source file:org.bigtester.ate.xmlschema.BaseElementFinderBeanDefinitionParser.java
/** * {@inheritDoc}//from ww w . j a va2 s .c om */ @Override protected @Nullable AbstractBeanDefinition parseInternal(@Nullable Element element, @Nullable ParserContext parserContext) { if (parserContext == null || element == null) throw GlobalUtils.createNotInitializedException("element and parserContext"); BeanDefinitionHolder holder = parserContext.getDelegate().parseBeanDefinitionElement(element); BeanDefinition bDef = holder.getBeanDefinition(); String findbyValue = element.getAttribute(XsdElementConstants.ATTR_GENERICELEMENTFIND_FINDBYVALUE); if (StringUtils.hasText(findbyValue)) bDef.getConstructorArgumentValues().addGenericArgumentValue(findbyValue); String strIndex = element.getAttribute(XsdElementConstants.ATTR_GENERICELEMENTFIND_INDEXOFSAMEELEMENTS); if (StringUtils.hasText(strIndex)) { bDef.getPropertyValues().addPropertyValue( XsdElementConstants.ATTR_GENERICELEMENTFIND_INDEXOFSAMEELEMENTS, new RuntimeBeanReference(strIndex)); } bDef.setAttribute("id", element.getAttribute("id")); return (AbstractBeanDefinition) bDef; }
From source file:com.mtgi.analytics.aop.config.v11.BtManagerBeanDefinitionParser.java
@Override protected void transform(ConfigurableListableBeanFactory factory, BeanDefinition template, Element element, ParserContext parserContext) {/*from ww w . j av a 2 s.co m*/ ManagerComponentDefinition def = (ManagerComponentDefinition) parserContext.getContainingComponent(); String managerId = overrideAttribute(ATT_ID, template, element); if (managerId == null) template.setAttribute(ATT_ID, managerId = "defaultTrackingManager"); if ("false".equals(element.getAttribute(ATT_ENABLED))) { //manager is disabled. replace definition with dummy instance. template.setBeanClassName(DisabledBehaviorTrackingManager.class.getName()); //clear properties and attributes. for (String att : template.attributeNames()) if (!ATT_ID.equals(att)) template.removeAttribute(att); template.getPropertyValues().clear(); //terminate immediately, do not parse any nested definitions (persisters, AOP config, context beans, etc) return; } overrideProperty(ATT_APPLICATION, template, element, false); overrideProperty(ATT_FLUSH_THRESHOLD, template, element, false); //wake up MBeanExporter if we're going to be doing MBean registration. if ("true".equalsIgnoreCase(element.getAttribute(ATT_REGISTER_MBEANS))) { AbstractBeanDefinition exporter = (AbstractBeanDefinition) factory .getBeanDefinition(CONFIG_MBEAN_EXPORTER); exporter.setLazyInit(false); //append manager ID to mbean name, in case of multiple managers in a single application. BeanDefinition naming = factory.getBeanDefinition(CONFIG_NAMING_STRATEGY); naming.getPropertyValues().addPropertyValue("value", managerId); } //prefer references to beans in the parent factory if they've been specified if (element.hasAttribute(ATT_MBEAN_SERVER)) factory.registerAlias(element.getAttribute(ATT_MBEAN_SERVER), CONFIG_MBEAN_SERVER); if (element.hasAttribute(ATT_SCHEDULER)) factory.registerAlias(element.getAttribute(ATT_SCHEDULER), CONFIG_SCHEDULER); if (element.hasAttribute(ATT_TASK_EXECUTOR)) factory.registerAlias(element.getAttribute(ATT_TASK_EXECUTOR), CONFIG_EXECUTOR); //make note of external persister element so that we don't activate log rotation. if (element.hasAttribute(ATT_PERSISTER)) { def.addNestedProperty(ATT_PERSISTER); MutablePropertyValues props = template.getPropertyValues(); props.removePropertyValue(ATT_PERSISTER); props.addPropertyValue(ATT_PERSISTER, new RuntimeBeanReference(element.getAttribute(ATT_PERSISTER))); } if (element.hasAttribute(ATT_SESSION_CONTEXT)) { //override default session context with reference def.addNestedProperty("sessionContext"); factory.registerAlias(element.getAttribute(ATT_SESSION_CONTEXT), CONFIG_SESSION_CONTEXT); } //handle AOP configuration if needed if (element.hasAttribute(ATT_METHOD_EXPRESSION)) { //activate global AOP proxying if it hasn't already been done (borrowed logic from AopNamespaceHandler / config element parser) activateAopProxies(parserContext, element); //register pointcut definition for the provided expression. RootBeanDefinition pointcut = new RootBeanDefinition(AspectJExpressionPointcut.class); //rely on deprecated method to maintain spring 2.0 support pointcut.setSingleton(false); pointcut.setSynthetic(true); pointcut.getPropertyValues().addPropertyValue("expression", element.getAttribute(ATT_METHOD_EXPRESSION)); //create implicit pointcut advice bean. RootBeanDefinition advice = new RootBeanDefinition(BehaviorTrackingAdvice.class); advice.getPropertyValues().addPropertyValue("trackingManager", new RuntimeBeanReference(managerId)); //register advice, pointcut, and advisor entry to bind the two together. XmlReaderContext ctx = parserContext.getReaderContext(); String pointcutId = ctx.registerWithGeneratedName(pointcut); String adviceId = ctx.registerWithGeneratedName(advice); RootBeanDefinition advisorDefinition = new RootBeanDefinition(DefaultBeanFactoryPointcutAdvisor.class); advisorDefinition.getPropertyValues().addPropertyValue("adviceBeanName", new RuntimeBeanNameReference(adviceId)); advisorDefinition.getPropertyValues().addPropertyValue("pointcut", new RuntimeBeanReference(pointcutId)); ctx.registerWithGeneratedName(advisorDefinition); } //configure flush trigger and job to be globally unique based on manager name. BeanDefinition flushTrigger = factory.getBeanDefinition("com.mtgi.analytics.btFlushTrigger"); SchedulerActivationPostProcessor.configureTriggerDefinition(flushTrigger, element.getAttribute(ATT_FLUSH_SCHEDULE), managerId + "_flush"); //set up a post-processor to register the flush job with the selected scheduler instance. the job and scheduler //come from the template factory, but the post-processor runs when the currently-parsing factory is finished. SchedulerActivationPostProcessor.registerPostProcessor(parserContext, factory, CONFIG_SCHEDULER, CONFIG_NAMESPACE + ".btFlushTrigger"); //ManagerComponentDefinition is a flag to nested parsers that they should push their parsed bean definitions into //the manager bean definition. for example, see BtPersisterBeanDefinitionParser. //descend on nested child nodes to pick up persister and session context configuration NodeList children = element.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { Node node = children.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { String namespaceUri = node.getNamespaceURI(); NamespaceHandler handler = parserContext.getReaderContext().getNamespaceHandlerResolver() .resolve(namespaceUri); ParserContext nestedCtx = new ParserContext(parserContext.getReaderContext(), parserContext.getDelegate(), template); nestedCtx.pushContainingComponent(def); handler.parse((Element) node, nestedCtx); } } if (!def.nestedProperties.contains(ATT_PERSISTER)) { //no persister registered. schedule default log rotation trigger. BtXmlPersisterBeanDefinitionParser.configureLogRotation(parserContext, factory, null); } if (!def.nestedProperties.contains("sessionContext")) { //custom session context not registered. select appropriate default class //depending on whether we are in a web context or not. if (parserContext.getReaderContext().getReader().getResourceLoader() instanceof WebApplicationContext) { BeanDefinition scDef = factory.getBeanDefinition(CONFIG_SESSION_CONTEXT); scDef.setBeanClassName(SpringSessionContext.class.getName()); } } }
From source file:com.github.yulechen.springannotation.test.ConfigurationClassUtils.java
/** * Check whether the given bean definition is a candidate for a * configuration class (or a nested component class declared within a * configuration/component class, to be auto-registered as well), and mark * it accordingly.//from w w w . ja va 2 s . co m * * @param beanDef * the bean definition to check * @param metadataReaderFactory * the current factory in use by the caller * @return whether the candidate qualifies as (any kind of) configuration * class */ public static boolean checkConfigurationClassCandidate(BeanDefinition beanDef, MetadataReaderFactory metadataReaderFactory) { String className = beanDef.getBeanClassName(); if (className == null) { return false; } AnnotationMetadata metadata; if (beanDef instanceof AnnotatedBeanDefinition && className.equals(((AnnotatedBeanDefinition) beanDef).getMetadata().getClassName())) { // Can reuse the pre-parsed metadata from the given // BeanDefinition... metadata = ((AnnotatedBeanDefinition) beanDef).getMetadata(); } else if (beanDef instanceof AbstractBeanDefinition && ((AbstractBeanDefinition) beanDef).hasBeanClass()) { // Check already loaded Class if present... // since we possibly can't even load the class file for this Class. Class<?> beanClass = ((AbstractBeanDefinition) beanDef).getBeanClass(); metadata = new StandardAnnotationMetadata(beanClass, true); } else { try { MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(className); metadata = metadataReader.getAnnotationMetadata(); } catch (IOException ex) { if (logger.isDebugEnabled()) { logger.debug( "Could not find class file for introspecting configuration annotations: " + className, ex); } return false; } } if (isFullConfigurationCandidate(metadata)) { beanDef.setAttribute(CONFIGURATION_CLASS_ATTRIBUTE, CONFIGURATION_CLASS_FULL); } else if (isLiteConfigurationCandidate(metadata)) { beanDef.setAttribute(CONFIGURATION_CLASS_ATTRIBUTE, CONFIGURATION_CLASS_LITE); } else { return false; } // It's a full or lite configuration candidate... Let's determine the // order value, if any. Map<String, Object> orderAttributes = metadata.getAnnotationAttributes(Order.class.getName()); if (orderAttributes != null) { beanDef.setAttribute(ORDER_ATTRIBUTE, orderAttributes.get(AnnotationUtils.VALUE)); } return true; }