@Override public BeanDefinitionHolder decorate(Node node, BeanDefinitionHolder definition, ParserContext parserContext) { // 设置bean scope为version-refresh definition.getBeanDefinition().setScope(VersionRefreshScope.SCOPE_NAME); String[] dependsOn = null; if (node instanceof Element) { Element ele = (Element) node; if (ele.hasAttribute(DEPENDS_ON)) { dependsOn = StringUtils.tokenizeToStringArray(ele.getAttribute(DEPENDS_ON), ","); } } // 注册属性依赖 DependencyConfigUtils.registerDependency(parserContext.getRegistry(), definition.getBeanName(), dependsOn); return definition; }
@Override public BeanDefinitionHolder decorate(Node node, BeanDefinitionHolder definition, ParserContext parserContext) { String propertyName = null; String converterClassName = null; if (node instanceof Element) { Element ele = (Element) node; if (ele.hasAttribute(PROPERTY_NAME)) { propertyName = ele.getAttribute(PROPERTY_NAME); } if (ele.hasAttribute(CONVERTER)) { converterClassName = ele.getAttribute(CONVERTER); } } // 为配置bean设置factory method Class<?> converterType = null; if (StringUtils.isNotEmpty(converterClassName)) { converterType = ClassUtils.resolveClassName(converterClassName, parserContext.getReaderContext().getBeanClassLoader()); } ConfigBeanConfigUtils.setConfigBeanFactoryMethod(parserContext.getRegistry(), definition.getBeanName(), definition.getBeanDefinition(), propertyName, converterType); // 注册属性依赖 DependencyConfigUtils.registerDependency(parserContext.getRegistry(), definition.getBeanName(), new String[]{propertyName}); return definition; }
private void addRefIfNeeded(Object v, List<String> refs) { if(v == null) return; if(v instanceof RuntimeBeanReference) { RuntimeBeanReference r = (RuntimeBeanReference)v; String name = r.getBeanName(); addRefIfNeeded(name, refs); if(name == null || name.length() == 0) { System.err.println("Warning - empty reference " + r); } } else if(v instanceof BeanDefinitionHolder) { // Nested bean definition BeanDefinitionHolder bdh = (BeanDefinitionHolder)v; processBeanDefinition(bdh.getBeanName(), bdh.getBeanDefinition()); } else if(v instanceof ManagedList<?>) { ManagedList<?> ml = (ManagedList<?>)v; for(Object le : ml) { addRefIfNeeded(le, refs); } // } else { // System.err.println(v.getClass()); } }
private Optional<RuntimeBeanReference> parseRefOrBean(Element elem, ParserContext ctx) { if (elem != null) { String ref = elem.getAttribute("ref").trim(); Element beanEl = getChildElementByTagName(elem, "bean"); if (!ref.isEmpty() && beanEl != null) { String name = elem.getLocalName(); ctx.getReaderContext().error('<' + name + ">'s 'ref' attribute can't be mixed with nested <bean> element.", elem); } else if (!ref.isEmpty()) { return Optional.of(new RuntimeBeanReference(ref)); } else if (beanEl != null) { BeanDefinitionHolder holder = ctx.getDelegate().parseBeanDefinitionElement(beanEl); ctx.registerBeanComponent(new BeanComponentDefinition(holder.getBeanDefinition(), holder.getBeanName())); return Optional.of(new RuntimeBeanReference(holder.getBeanName())); } } return Optional.empty(); }
@Override public Set<BeanDefinitionHolder> doScan(String... basePackages) { Set<BeanDefinitionHolder> beanDefinitions = super.doScan(basePackages); if (beanDefinitions.isEmpty()) { logger.warn("No mapper was found in '" + Arrays.toString(basePackages) + "' package. Please check your configuration."); } else { for (BeanDefinitionHolder holder : beanDefinitions) { GenericBeanDefinition definition = (GenericBeanDefinition) holder.getBeanDefinition(); if (logger.isDebugEnabled()) { logger.debug("Creating MapperFactoryBean with name '" + holder.getBeanName() + "' and '" + definition.getBeanClassName() + "' mapperInterface"); } definition.getPropertyValues().add("mapperProxy", getRegistry().getBeanDefinition("mapperProxy")); definition.getPropertyValues().add("mapperInterface", definition.getBeanClassName()); definition.setBeanClass(MapperFactoryBean.class); definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE); } } return beanDefinitions; }
public static BeanDefinitionHolder register(Element ele, BeanDefinitionHolder bdHolder, ParserContext parserContext) { if (bdHolder != null) { String name = bdHolder.getBeanName(); checkReservedName(name, ele, parserContext); checkUniqueName(name, parserContext.getRegistry()); try { // add non-lenient constructor resolution BeanDefinition beanDefinition = bdHolder.getBeanDefinition(); if (beanDefinition instanceof AbstractBeanDefinition) { AbstractBeanDefinition abd = (AbstractBeanDefinition) beanDefinition; abd.setLenientConstructorResolution(false); abd.setNonPublicAccessAllowed(false); } // Register the final decorated instance. BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, parserContext.getRegistry()); } catch (BeanDefinitionStoreException ex) { parserContext.getReaderContext().error( "Failed to register bean definition with name '" + bdHolder.getBeanName() + "'", ele, ex); } // register component (and send registration events) parserContext.registerComponent(new BeanComponentDefinition(bdHolder)); } return bdHolder; }
public static BeanDefinitionHolder decorateIfRequired(Node node, BeanDefinitionHolder originalDef, ParserContext parserContext) { String namespaceUri = node.getNamespaceURI(); if (!parserContext.getDelegate().isDefaultNamespace(namespaceUri) && !isRFC124Namespace(namespaceUri)) { NamespaceHandler handler = parserContext.getReaderContext().getNamespaceHandlerResolver().resolve(namespaceUri); if (handler != null) { return handler.decorate(node, originalDef, new ParserContext(parserContext.getReaderContext(), parserContext.getDelegate())); } else if (namespaceUri.startsWith("http://www.springframework.org/")) { parserContext.getReaderContext().error( "Unable to locate Spring NamespaceHandler for XML schema namespace [" + namespaceUri + "]", node); } else { // A custom namespace, not to be handled by Spring - maybe "xml:...". } } return originalDef; }
@Override public BeanDefinition parse(Element element, ParserContext parserContext) { Object source = parserContext.extractSource(element); // Obtain bean definitions for all relevant BeanPostProcessors. Set<BeanDefinitionHolder> processorDefinitions = AnnotationConfigUtils.registerAnnotationConfigProcessors(parserContext.getRegistry(), source); // Register component for the surrounding <context:annotation-config> element. CompositeComponentDefinition compDefinition = new CompositeComponentDefinition(element.getTagName(), source); parserContext.pushContainingComponent(compDefinition); // Nest the concrete beans in the surrounding component. for (BeanDefinitionHolder processorDefinition : processorDefinitions) { parserContext.registerComponent(new BeanComponentDefinition(processorDefinition)); } // Finally register the composite component. parserContext.popAndRegisterContainingComponent(); return null; }
public void parse(Set<BeanDefinitionHolder> configCandidates) { for (BeanDefinitionHolder holder : configCandidates) { BeanDefinition bd = holder.getBeanDefinition(); try { if (bd instanceof AbstractBeanDefinition && ((AbstractBeanDefinition) bd).hasBeanClass()) { parse(((AbstractBeanDefinition) bd).getBeanClass(), holder.getBeanName()); } else { parse(bd.getBeanClassName(), holder.getBeanName()); } } catch (IOException ex) { throw new BeanDefinitionStoreException("Failed to load bean class: " + bd.getBeanClassName(), ex); } } processDeferredImportSelectors(); }
protected void registerComponents( XmlReaderContext readerContext, Set<BeanDefinitionHolder> beanDefinitions, Element element) { Object source = readerContext.extractSource(element); CompositeComponentDefinition compositeDef = new CompositeComponentDefinition(element.getTagName(), source); for (BeanDefinitionHolder beanDefHolder : beanDefinitions) { compositeDef.addNestedComponent(new BeanComponentDefinition(beanDefHolder)); } // Register annotation config processors, if necessary. boolean annotationConfig = true; if (element.hasAttribute(ANNOTATION_CONFIG_ATTRIBUTE)) { annotationConfig = Boolean.valueOf(element.getAttribute(ANNOTATION_CONFIG_ATTRIBUTE)); } if (annotationConfig) { Set<BeanDefinitionHolder> processorDefinitions = AnnotationConfigUtils.registerAnnotationConfigProcessors(readerContext.getRegistry(), source); for (BeanDefinitionHolder processorDefinition : processorDefinitions) { compositeDef.addNestedComponent(new BeanComponentDefinition(processorDefinition)); } } readerContext.fireComponentRegistered(compositeDef); }
/** * 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; }
/** * Determine whether the provided bean definition is an autowire candidate. * <p>To be considered a candidate the bean's <em>autowire-candidate</em> * attribute must not have been set to 'false'. Also, if an annotation on * the field or parameter to be autowired is recognized by this bean factory * as a <em>qualifier</em>, the bean must 'match' against the annotation as * well as any attributes it may contain. The bean definition must contain * the same qualifier or match by meta attributes. A "value" attribute will * fallback to match against the bean name or an alias if a qualifier or * attribute does not match. * @see Qualifier */ @Override public boolean isAutowireCandidate(BeanDefinitionHolder bdHolder, DependencyDescriptor descriptor) { boolean match = super.isAutowireCandidate(bdHolder, descriptor); if (match && descriptor != null) { match = checkQualifiers(bdHolder, descriptor.getAnnotations()); if (match) { MethodParameter methodParam = descriptor.getMethodParameter(); if (methodParam != null) { Method method = methodParam.getMethod(); if (method == null || void.class.equals(method.getReturnType())) { match = checkQualifiers(bdHolder, methodParam.getMethodAnnotations()); } } } } return match; }
/** * Register the given bean definition with the given bean factory. * @param definitionHolder the bean definition including name and aliases * @param registry the bean factory to register with * @throws BeanDefinitionStoreException if registration failed */ public static void registerBeanDefinition( BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry) throws BeanDefinitionStoreException { // Register bean definition under primary name. String beanName = definitionHolder.getBeanName(); registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition()); // Register aliases for bean name, if any. String[] aliases = definitionHolder.getAliases(); if (aliases != null) { for (String aliase : aliases) { registry.registerAlias(beanName, aliase); } } }
/** * Determine whether the specified bean definition qualifies as an autowire candidate, * to be injected into other beans which declare a dependency of matching type. * @param beanName the name of the bean definition to check * @param mbd the merged bean definition to check * @param descriptor the descriptor of the dependency to resolve * @param resolver the AutowireCandidateResolver to use for the actual resolution algorithm * @return whether the bean should be considered as autowire candidate */ protected boolean isAutowireCandidate(String beanName, RootBeanDefinition mbd, DependencyDescriptor descriptor, AutowireCandidateResolver resolver) { String beanDefinitionName = BeanFactoryUtils.transformedBeanName(beanName); resolveBeanClass(mbd, beanDefinitionName); if (mbd.isFactoryMethodUnique) { boolean resolve; synchronized (mbd.constructorArgumentLock) { resolve = (mbd.resolvedConstructorOrFactoryMethod == null); } if (resolve) { new ConstructorResolver(this).resolveFactoryMethodIfPossible(mbd); } } return resolver.isAutowireCandidate( new BeanDefinitionHolder(mbd, beanName, getAliases(beanDefinitionName)), descriptor); }
/** * Process the given bean element, parsing the bean definition * and registering it with the registry. */ protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) { BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele); if (bdHolder != null) { bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder); try { // Register the final decorated instance. BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry()); } catch (BeanDefinitionStoreException ex) { getReaderContext().error("Failed to register bean definition with name '" + bdHolder.getBeanName() + "'", ele, ex); } // Send registration event. getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder)); } }
public BeanDefinitionHolder decorateIfRequired( Node node, BeanDefinitionHolder originalDef, BeanDefinition containingBd) { String namespaceUri = getNamespaceURI(node); if (!isDefaultNamespace(namespaceUri)) { NamespaceHandler handler = this.readerContext.getNamespaceHandlerResolver().resolve(namespaceUri); if (handler != null) { return handler.decorate(node, originalDef, new ParserContext(this.readerContext, this, containingBd)); } else if (namespaceUri != null && namespaceUri.startsWith("http://www.springframework.org/")) { error("Unable to locate Spring NamespaceHandler for XML schema namespace [" + namespaceUri + "]", node); } else { // A custom namespace, not to be handled by Spring - maybe "xml:...". if (logger.isDebugEnabled()) { logger.debug("No Spring NamespaceHandler found for XML schema namespace [" + namespaceUri + "]"); } } } return originalDef; }
@Override public BeanDefinitionHolder decorate(Node node, BeanDefinitionHolder definition, ParserContext parserContext) { if (node instanceof Attr) { Attr attr = (Attr) node; String propertyName = parserContext.getDelegate().getLocalName(attr); String propertyValue = attr.getValue(); MutablePropertyValues pvs = definition.getBeanDefinition().getPropertyValues(); if (pvs.contains(propertyName)) { parserContext.getReaderContext().error("Property '" + propertyName + "' is already defined using " + "both <property> and inline syntax. Only one approach may be used per property.", attr); } if (propertyName.endsWith(REF_SUFFIX)) { propertyName = propertyName.substring(0, propertyName.length() - REF_SUFFIX.length()); pvs.add(Conventions.attributeNameToPropertyName(propertyName), new RuntimeBeanReference(propertyValue)); } else { pvs.add(Conventions.attributeNameToPropertyName(propertyName), propertyValue); } } return definition; }
private void findInnerBeanDefinitionsAndBeanReferences(BeanDefinition beanDefinition) { List<BeanDefinition> innerBeans = new ArrayList<BeanDefinition>(); List<BeanReference> references = new ArrayList<BeanReference>(); PropertyValues propertyValues = beanDefinition.getPropertyValues(); for (int i = 0; i < propertyValues.getPropertyValues().length; i++) { PropertyValue propertyValue = propertyValues.getPropertyValues()[i]; Object value = propertyValue.getValue(); if (value instanceof BeanDefinitionHolder) { innerBeans.add(((BeanDefinitionHolder) value).getBeanDefinition()); } else if (value instanceof BeanDefinition) { innerBeans.add((BeanDefinition) value); } else if (value instanceof BeanReference) { references.add((BeanReference) value); } } this.innerBeanDefinitions = innerBeans.toArray(new BeanDefinition[innerBeans.size()]); this.beanReferences = references.toArray(new BeanReference[references.size()]); }
@Override public BeanDefinitionHolder decorate(Node node, BeanDefinitionHolder definition, ParserContext parserContext) { boolean proxyTargetClass = true; if (node instanceof Element) { Element ele = (Element) node; if (ele.hasAttribute(PROXY_TARGET_CLASS)) { proxyTargetClass = Boolean.valueOf(ele.getAttribute(PROXY_TARGET_CLASS)); } } // Register the original bean definition as it will be referenced by the scoped proxy // and is relevant for tooling (validation, navigation). BeanDefinitionHolder holder = ScopedProxyUtils.createScopedProxy(definition, parserContext.getRegistry(), proxyTargetClass); String targetBeanName = ScopedProxyUtils.getTargetBeanName(definition.getBeanName()); parserContext.getReaderContext().fireComponentRegistered( new BeanComponentDefinition(definition.getBeanDefinition(), targetBeanName)); return holder; }
public BeanDefinitionHolder decorate(Node node, BeanDefinitionHolder definition, ParserContext parserContext) { Element element = (Element) node; String type = element.getAttribute("type"); String className = element.getAttribute("class"); String javascriptClassName = element.getAttribute("javascript"); BeanDefinitionRegistry registry = parserContext.getRegistry(); ConverterConfig converterConfig = new ConverterConfig(); converterConfig.setType(type); converterConfig.setJavascriptClassName(javascriptClassName); parseConverterSettings(converterConfig, element); lookupConverters(registry).put(className, converterConfig); return definition; }
public BeanDefinitionHolder decorate(Node node, BeanDefinitionHolder definition, ParserContext parserContext) { BeanDefinitionRegistry registry = parserContext.getRegistry(); BeanDefinition config = registerSpringConfiguratorIfNecessary(registry); StringBuffer sigtext = new StringBuffer(); NodeList children = node.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { Node child = children.item(i); if (child.getNodeType() != Node.TEXT_NODE && child.getNodeType() != Node.CDATA_SECTION_NODE) { log.warn("Ignoring illegal node type: " + child.getNodeType()); continue; } sigtext.append(child.getNodeValue()); } config.getPropertyValues().addPropertyValue("signatures", sigtext.toString()); return definition; }
/** * Parses the <code><dwr:init></code> tag checking for nested creator and converter definitions. */ public BeanDefinitionHolder decorate(Node initElement, BeanDefinitionHolder configuration, ParserContext parserContext) { NodeList inits = initElement.getChildNodes(); Map<String, String> converters = new HashMap<String, String>(); for (int index = 0; index < inits.getLength(); index++) { Node node = inits.item(index); if (node instanceof Element) { Element child = (Element) node; if (ELEMENT_CONVERTER.equals(node.getNodeName())) { converters.put(child.getAttribute(ATTRIBUTE_ID), child.getAttribute(ATTRIBUTE_CLASS)); } } } configuration.getBeanDefinition().getPropertyValues().addPropertyValue("converterTypes", converters); return configuration; }
/** * Determine whether the provided bean definition is an autowire candidate. * <p>To be considered a candidate the bean's <em>autowire-candidate</em> * attribute must not have been set to 'false'. Also, if an annotation on * the field or parameter to be autowired is recognized by this bean factory * as a <em>qualifier</em>, the bean must 'match' against the annotation as * well as any attributes it may contain. The bean definition must contain * the same qualifier or match by meta attributes. A "value" attribute will * fallback to match against the bean name or an alias if a qualifier or * attribute does not match. * @see Qualifier */ @Override public boolean isAutowireCandidate(BeanDefinitionHolder bdHolder, DependencyDescriptor descriptor) { boolean match = super.isAutowireCandidate(bdHolder, descriptor); if (match && descriptor != null) { match = checkQualifiers(bdHolder, descriptor.getAnnotations()); if (match) { MethodParameter methodParam = descriptor.getMethodParameter(); if (methodParam != null) { Method method = methodParam.getMethod(); if (method == null || void.class == method.getReturnType()) { match = checkQualifiers(bdHolder, methodParam.getMethodAnnotations()); } } } } return match; }
/** * Register the {@link Configuration} class itself as a bean definition. */ private void registerBeanDefinitionForImportedConfigurationClass(ConfigurationClass configClass) { AnnotationMetadata metadata = configClass.getMetadata(); AnnotatedGenericBeanDefinition configBeanDef = new AnnotatedGenericBeanDefinition(metadata); ScopeMetadata scopeMetadata = scopeMetadataResolver.resolveScopeMetadata(configBeanDef); configBeanDef.setScope(scopeMetadata.getScopeName()); String configBeanName = this.importBeanNameGenerator.generateBeanName(configBeanDef, this.registry); AnnotationConfigUtils.processCommonDefinitionAnnotations(configBeanDef, metadata); BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(configBeanDef, configBeanName); definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry); this.registry.registerBeanDefinition(definitionHolder.getBeanName(), definitionHolder.getBeanDefinition()); configClass.setBeanName(configBeanName); if (logger.isDebugEnabled()) { logger.debug("Registered bean definition for imported class '" + configBeanName + "'"); } }
@Test public void testAutowiredMethodParameterWithStaticallyQualifiedCandidate() { GenericApplicationContext context = new GenericApplicationContext(); ConstructorArgumentValues cavs = new ConstructorArgumentValues(); cavs.addGenericArgumentValue(JUERGEN); RootBeanDefinition person = new RootBeanDefinition(QualifiedPerson.class, cavs, null); context.registerBeanDefinition(JUERGEN, ScopedProxyUtils.createScopedProxy(new BeanDefinitionHolder(person, JUERGEN), context, true).getBeanDefinition()); context.registerBeanDefinition("autowired", new RootBeanDefinition(QualifiedMethodParameterTestBean.class)); AnnotationConfigUtils.registerAnnotationConfigProcessors(context); context.refresh(); QualifiedMethodParameterTestBean bean = (QualifiedMethodParameterTestBean) context.getBean("autowired"); assertEquals(JUERGEN, bean.getPerson().getName()); }
private ManagedList<?> getCallableInterceptors(Element element, Object source, ParserContext parserContext) { ManagedList<? super Object> interceptors = new ManagedList<Object>(); Element asyncElement = DomUtils.getChildElementByTagName(element, "async-support"); if (asyncElement != null) { Element interceptorsElement = DomUtils.getChildElementByTagName(asyncElement, "callable-interceptors"); if (interceptorsElement != null) { interceptors.setSource(source); for (Element converter : DomUtils.getChildElementsByTagName(interceptorsElement, "bean")) { BeanDefinitionHolder beanDef = parserContext.getDelegate().parseBeanDefinitionElement(converter); beanDef = parserContext.getDelegate().decorateBeanDefinitionIfRequired(converter, beanDef); interceptors.add(beanDef); } } } return interceptors; }
private ManagedList<?> getDeferredResultInterceptors(Element element, Object source, ParserContext parserContext) { ManagedList<? super Object> interceptors = new ManagedList<Object>(); Element asyncElement = DomUtils.getChildElementByTagName(element, "async-support"); if (asyncElement != null) { Element interceptorsElement = DomUtils.getChildElementByTagName(asyncElement, "deferred-result-interceptors"); if (interceptorsElement != null) { interceptors.setSource(source); for (Element converter : DomUtils.getChildElementsByTagName(interceptorsElement, "bean")) { BeanDefinitionHolder beanDef = parserContext.getDelegate().parseBeanDefinitionElement(converter); beanDef = parserContext.getDelegate().decorateBeanDefinitionIfRequired(converter, beanDef); interceptors.add(beanDef); } } } return interceptors; }
private ManagedList<Object> wrapLegacyResolvers(List<Object> list, ParserContext context) { ManagedList<Object> result = new ManagedList<Object>(); for (Object object : list) { if (object instanceof BeanDefinitionHolder) { BeanDefinitionHolder beanDef = (BeanDefinitionHolder) object; String className = beanDef.getBeanDefinition().getBeanClassName(); Class<?> clazz = ClassUtils.resolveClassName(className, context.getReaderContext().getBeanClassLoader()); if (WebArgumentResolver.class.isAssignableFrom(clazz)) { RootBeanDefinition adapter = new RootBeanDefinition(ServletWebArgumentResolverAdapter.class); adapter.getConstructorArgumentValues().addIndexedArgumentValue(0, beanDef); result.add(new BeanDefinitionHolder(adapter, beanDef.getBeanName() + "Adapter")); continue; } } result.add(object); } return result; }
@Test public void testGetAnonymousInnerBeanFromScope() throws Exception { TestBean bean = (TestBean) this.beanFactory.getBean("outerBean"); assertFalse(AopUtils.isAopProxy(bean)); assertTrue(AopUtils.isCglibProxy(bean.getSpouse())); BeanDefinition beanDef = this.beanFactory.getBeanDefinition("outerBean"); BeanDefinitionHolder innerBeanDef = (BeanDefinitionHolder) beanDef.getPropertyValues().getPropertyValue("spouse").getValue(); String name = innerBeanDef.getBeanName(); MockHttpServletRequest request = new MockHttpServletRequest(); RequestAttributes requestAttributes = new ServletRequestAttributes(request); RequestContextHolder.setRequestAttributes(requestAttributes); try { assertNull(request.getAttribute("scopedTarget." + name)); assertEquals("scoped", bean.getSpouse().getName()); assertNotNull(request.getAttribute("scopedTarget." + name)); assertEquals(TestBean.class, request.getAttribute("scopedTarget." + name).getClass()); assertEquals("scoped", ((TestBean) request.getAttribute("scopedTarget." + name)).getName()); } finally { RequestContextHolder.setRequestAttributes(null); } }
/** * Register the given bean definition with the given bean factory. * @param definitionHolder the bean definition including name and aliases * @param registry the bean factory to register with * @throws BeanDefinitionStoreException if registration failed */ public static void registerBeanDefinition( BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry) throws BeanDefinitionStoreException { // Register bean definition under primary name. String beanName = definitionHolder.getBeanName(); registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition()); // Register aliases for bean name, if any. String[] aliases = definitionHolder.getAliases(); if (aliases != null) { for (String alias : aliases) { registry.registerAlias(beanName, alias); } } }