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()]); }
private void unwrapDefinitions(BeanDefinition advisorDefinition, BeanDefinition pointcutDefinition) { MutablePropertyValues pvs = advisorDefinition.getPropertyValues(); BeanReference adviceReference = (BeanReference) pvs.getPropertyValue("adviceBeanName").getValue(); if (pointcutDefinition != null) { this.beanReferences = new BeanReference[] {adviceReference}; this.beanDefinitions = new BeanDefinition[] {advisorDefinition, pointcutDefinition}; this.description = buildDescription(adviceReference, pointcutDefinition); } else { BeanReference pointcutReference = (BeanReference) pvs.getPropertyValue("pointcut").getValue(); this.beanReferences = new BeanReference[] {adviceReference, pointcutReference}; this.beanDefinitions = new BeanDefinition[] {advisorDefinition}; this.description = buildDescription(adviceReference, pointcutReference); } }
@Test public void parseInternal_singleElementWithCustomAmazonEc2Client_userTagMapCreatedWithCustomEc2Client() throws Exception { //Arrange DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(beanFactory); //Act reader.loadBeanDefinitions(new ClassPathResource(getClass().getSimpleName() + "-customEc2Client.xml", getClass())); //Assert assertTrue(beanFactory.containsBeanDefinition("myUserTags")); ConstructorArgumentValues.ValueHolder valueHolder = beanFactory.getBeanDefinition("myUserTags"). getConstructorArgumentValues().getArgumentValue(0, BeanReference.class); BeanReference beanReference = (BeanReference) valueHolder.getValue(); assertEquals("amazonEC2Client", beanReference.getBeanName()); assertFalse(beanFactory.containsBeanDefinition(AmazonWebserviceClientConfigurationUtils.getBeanName(AmazonEC2Client.class.getName()))); }
private AspectComponentDefinition createAspectComponentDefinition( Element aspectElement, String aspectId, List<BeanDefinition> beanDefs, List<BeanReference> beanRefs, ParserContext parserContext) { BeanDefinition[] beanDefArray = beanDefs.toArray(new BeanDefinition[beanDefs.size()]); BeanReference[] beanRefArray = beanRefs.toArray(new BeanReference[beanRefs.size()]); Object source = parserContext.extractSource(aspectElement); return new AspectComponentDefinition(aspectId, beanDefArray, beanRefArray, source); }
public AspectComponentDefinition( String aspectName, BeanDefinition[] beanDefinitions, BeanReference[] beanReferences, Object source) { super(aspectName, source); this.beanDefinitions = (beanDefinitions != null ? beanDefinitions : new BeanDefinition[0]); this.beanReferences = (beanReferences != null ? beanReferences : new BeanReference[0]); }
/** * JAVADOC Method Level Comments */ @Test public void testDoParse() { EnvironmentBeanDefinitionParser parser = new EnvironmentBeanDefinitionParser(); Element element = mock(Element.class); when(element.getAttribute("tokenFactory")).thenReturn("tokenFactory"); NodeList nodelist = mock(NodeList.class); when(nodelist.getLength()).thenReturn(2); Element defel = mock(Element.class); when(defel.getNodeName()).thenReturn("definition"); when(defel.getLocalName()).thenReturn(null); when(defel.getNodeValue()).thenReturn("simple.xml"); when(nodelist.item(0)).thenReturn(defel); Element lisel = mock(Element.class); when(lisel.getNodeName()).thenReturn("listenerRef"); when(lisel.getLocalName()).thenReturn(null); when(lisel.getNodeValue()).thenReturn("hohoListener"); when(nodelist.item(1)).thenReturn(lisel); when(element.getChildNodes()).thenReturn(nodelist); BeanDefinitionBuilder builder = mock(BeanDefinitionBuilder.class); when(builder.addPropertyReference("tokenFactory", "tokenFactory")).thenReturn(builder); when(builder.addPropertyValue("definitionResources", Collections.singletonList("simple.xml"))) .thenReturn(builder); List<BeanReference> lisnames = new ManagedList<BeanReference>(); lisnames.add(new RuntimeBeanReference("hohoListener")); when(builder.addPropertyValue("workflowListeners", lisnames)).thenReturn(builder); parser.doParse(element, builder); }
@Override public void postProcessBeanDefinitionRegistry( BeanDefinitionRegistry registry) throws BeansException { if (this.mongoTemplate == null) { if (this.repoId != null) { // Fetch the MongoTemplate Bean Id // BeanDefinition repo = registry.getBeanDefinition(this.repoId); this.templateId = ((BeanReference)repo.getPropertyValues().get("mongoOperations")).getBeanName(); } // Check to make sure we have a reference to the MongoTemplate // if (this.templateId == null) { throw new RuntimeException("Unable to obtain a reference to a MongoTemplate"); } } // Add in CascadeSupport // BeanDefinition mongoCascadeSupportBean = BeanDefinitionBuilder .genericBeanDefinition(MongoCascadeSupport.class) .getBeanDefinition(); ConstructorArgumentValues args = mongoCascadeSupportBean.getConstructorArgumentValues(); args.addIndexedArgumentValue(0, this); registry.registerBeanDefinition(Long.toString((new Random()).nextLong()), mongoCascadeSupportBean); }
@SuppressWarnings({"unchecked"}) protected static String findDefaultFilterChainBeanId(ParserContext parserContext) { BeanDefinition filterChainList = parserContext.getRegistry().getBeanDefinition(BeanIds.FILTER_CHAINS); // Get the list of SecurityFilterChain beans List<BeanReference> filterChains = (List<BeanReference>) filterChainList.getPropertyValues().getPropertyValue("sourceList").getValue(); return filterChains.get(filterChains.size() - 1).getBeanName(); }
/** * Given a bean name (assumed to implement {@link org.springframework.core.io.support.PropertiesLoaderSupport}) * checks whether it already references the <code>global-properties</code> bean. If not, 'upgrades' the bean by * appending all additional resources it mentions in its <code>locations</code> property to * <code>globalPropertyLocations</code>, except for those resources mentioned in <code>newLocations</code>. A * reference to <code>global-properties</code> will then be added and the resource list in * <code>newLocations<code> will then become the new <code>locations</code> list for the bean. * * @param beanFactory * the bean factory * @param globalPropertyLocations * the list of global property locations to be appended to * @param beanName * the bean name * @param newLocations * the new locations to be set on the bean * @return the mutable property values */ @SuppressWarnings("unchecked") private MutablePropertyValues processLocations(ConfigurableListableBeanFactory beanFactory, Collection<Object> globalPropertyLocations, String beanName, String[] newLocations) { // Get the bean an check its existing properties value MutablePropertyValues beanProperties = beanFactory.getBeanDefinition(beanName).getPropertyValues(); PropertyValue pv = beanProperties.getPropertyValue(LegacyConfigPostProcessor.PROPERTY_PROPERTIES); Object value; // If the properties value already references the global-properties bean, we have nothing else to do. Otherwise, // we have to 'upgrade' the bean definition. if (pv == null || (value = pv.getValue()) == null || !(value instanceof BeanReference) || ((BeanReference) value).getBeanName().equals(LegacyConfigPostProcessor.BEAN_NAME_GLOBAL_PROPERTIES)) { // Convert the array of new locations to a managed list of type string values, so that it is // compatible with a bean definition Collection<Object> newLocationList = new ManagedList(newLocations.length); if (newLocations != null && newLocations.length > 0) { for (String preserveLocation : newLocations) { newLocationList.add(new TypedStringValue(preserveLocation)); } } // If there is currently a locations list, process it pv = beanProperties.getPropertyValue(LegacyConfigPostProcessor.PROPERTY_LOCATIONS); if (pv != null && (value = pv.getValue()) != null && value instanceof Collection) { Collection<Object> locations = (Collection<Object>) value; // Compute the set of locations that need to be added to globalPropertyLocations (preserving order) and // warn about each Set<Object> addedLocations = new LinkedHashSet<Object>(locations); addedLocations.removeAll(globalPropertyLocations); addedLocations.removeAll(newLocationList); for (Object location : addedLocations) { LegacyConfigPostProcessor.logger.warn("Legacy configuration detected: adding " + (location instanceof TypedStringValue ? ((TypedStringValue) location).getValue() : location.toString()) + " to global-properties definition"); globalPropertyLocations.add(location); } } // Ensure the bean now references global-properties beanProperties.addPropertyValue(LegacyConfigPostProcessor.PROPERTY_PROPERTIES, new RuntimeBeanReference( LegacyConfigPostProcessor.BEAN_NAME_GLOBAL_PROPERTIES)); // Ensure the new location list is now set on the bean if (newLocationList.size() > 0) { beanProperties.addPropertyValue(LegacyConfigPostProcessor.PROPERTY_LOCATIONS, newLocationList); } else { beanProperties.removePropertyValue(LegacyConfigPostProcessor.PROPERTY_LOCATIONS); } } return beanProperties; }
/** * Returns an empty array. */ @Override public BeanReference[] getBeanReferences() { return new BeanReference[0]; }
@Override public BeanReference[] getBeanReferences() { return this.beanReferences; }
private void parseAspect(Element aspectElement, ParserContext parserContext) { String aspectId = aspectElement.getAttribute(ID); String aspectName = aspectElement.getAttribute(REF); try { this.parseState.push(new AspectEntry(aspectId, aspectName)); List<BeanDefinition> beanDefinitions = new ArrayList<BeanDefinition>(); List<BeanReference> beanReferences = new ArrayList<BeanReference>(); List<Element> declareParents = DomUtils.getChildElementsByTagName(aspectElement, DECLARE_PARENTS); for (int i = METHOD_INDEX; i < declareParents.size(); i++) { Element declareParentsElement = declareParents.get(i); beanDefinitions.add(parseDeclareParents(declareParentsElement, parserContext)); } // We have to parse "advice" and all the advice kinds in one loop, to get the // ordering semantics right. NodeList nodeList = aspectElement.getChildNodes(); boolean adviceFoundAlready = false; for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); if (isAdviceNode(node, parserContext)) { if (!adviceFoundAlready) { adviceFoundAlready = true; if (!StringUtils.hasText(aspectName)) { parserContext.getReaderContext().error( "<aspect> tag needs aspect bean reference via 'ref' attribute when declaring advices.", aspectElement, this.parseState.snapshot()); return; } beanReferences.add(new RuntimeBeanReference(aspectName)); } AbstractBeanDefinition advisorDefinition = parseAdvice( aspectName, i, aspectElement, (Element) node, parserContext, beanDefinitions, beanReferences); beanDefinitions.add(advisorDefinition); } } AspectComponentDefinition aspectComponentDefinition = createAspectComponentDefinition( aspectElement, aspectId, beanDefinitions, beanReferences, parserContext); parserContext.pushContainingComponent(aspectComponentDefinition); List<Element> pointcuts = DomUtils.getChildElementsByTagName(aspectElement, POINTCUT); for (Element pointcutElement : pointcuts) { parsePointcut(pointcutElement, parserContext); } parserContext.popAndRegisterContainingComponent(); } finally { this.parseState.pop(); } }
/** * Parses one of '{@code before}', '{@code after}', '{@code after-returning}', * '{@code after-throwing}' or '{@code around}' and registers the resulting * BeanDefinition with the supplied BeanDefinitionRegistry. * @return the generated advice RootBeanDefinition */ private AbstractBeanDefinition parseAdvice( String aspectName, int order, Element aspectElement, Element adviceElement, ParserContext parserContext, List<BeanDefinition> beanDefinitions, List<BeanReference> beanReferences) { try { this.parseState.push(new AdviceEntry(parserContext.getDelegate().getLocalName(adviceElement))); // create the method factory bean RootBeanDefinition methodDefinition = new RootBeanDefinition(MethodLocatingFactoryBean.class); methodDefinition.getPropertyValues().add("targetBeanName", aspectName); methodDefinition.getPropertyValues().add("methodName", adviceElement.getAttribute("method")); methodDefinition.setSynthetic(true); // create instance factory definition RootBeanDefinition aspectFactoryDef = new RootBeanDefinition(SimpleBeanFactoryAwareAspectInstanceFactory.class); aspectFactoryDef.getPropertyValues().add("aspectBeanName", aspectName); aspectFactoryDef.setSynthetic(true); // register the pointcut AbstractBeanDefinition adviceDef = createAdviceDefinition( adviceElement, parserContext, aspectName, order, methodDefinition, aspectFactoryDef, beanDefinitions, beanReferences); // configure the advisor RootBeanDefinition advisorDefinition = new RootBeanDefinition(AspectJPointcutAdvisor.class); advisorDefinition.setSource(parserContext.extractSource(adviceElement)); advisorDefinition.getConstructorArgumentValues().addGenericArgumentValue(adviceDef); if (aspectElement.hasAttribute(ORDER_PROPERTY)) { advisorDefinition.getPropertyValues().add( ORDER_PROPERTY, aspectElement.getAttribute(ORDER_PROPERTY)); } // register the final advisor parserContext.getReaderContext().registerWithGeneratedName(advisorDefinition); return advisorDefinition; } finally { this.parseState.pop(); } }
/** * Creates the RootBeanDefinition for a POJO advice bean. Also causes pointcut * parsing to occur so that the pointcut may be associate with the advice bean. * This same pointcut is also configured as the pointcut for the enclosing * Advisor definition using the supplied MutablePropertyValues. */ private AbstractBeanDefinition createAdviceDefinition( Element adviceElement, ParserContext parserContext, String aspectName, int order, RootBeanDefinition methodDef, RootBeanDefinition aspectFactoryDef, List<BeanDefinition> beanDefinitions, List<BeanReference> beanReferences) { RootBeanDefinition adviceDefinition = new RootBeanDefinition(getAdviceClass(adviceElement, parserContext)); adviceDefinition.setSource(parserContext.extractSource(adviceElement)); adviceDefinition.getPropertyValues().add(ASPECT_NAME_PROPERTY, aspectName); adviceDefinition.getPropertyValues().add(DECLARATION_ORDER_PROPERTY, order); if (adviceElement.hasAttribute(RETURNING)) { adviceDefinition.getPropertyValues().add( RETURNING_PROPERTY, adviceElement.getAttribute(RETURNING)); } if (adviceElement.hasAttribute(THROWING)) { adviceDefinition.getPropertyValues().add( THROWING_PROPERTY, adviceElement.getAttribute(THROWING)); } if (adviceElement.hasAttribute(ARG_NAMES)) { adviceDefinition.getPropertyValues().add( ARG_NAMES_PROPERTY, adviceElement.getAttribute(ARG_NAMES)); } ConstructorArgumentValues cav = adviceDefinition.getConstructorArgumentValues(); cav.addIndexedArgumentValue(METHOD_INDEX, methodDef); Object pointcut = parsePointcutProperty(adviceElement, parserContext); if (pointcut instanceof BeanDefinition) { cav.addIndexedArgumentValue(POINTCUT_INDEX, pointcut); beanDefinitions.add((BeanDefinition) pointcut); } else if (pointcut instanceof String) { RuntimeBeanReference pointcutRef = new RuntimeBeanReference((String) pointcut); cav.addIndexedArgumentValue(POINTCUT_INDEX, pointcutRef); beanReferences.add(pointcutRef); } cav.addIndexedArgumentValue(ASPECT_INSTANCE_FACTORY_INDEX, aspectFactoryDef); return adviceDefinition; }
private String buildDescription(BeanReference adviceReference, BeanDefinition pointcutDefinition) { return new StringBuilder("Advisor <advice(ref)='"). append(adviceReference.getBeanName()).append("', pointcut(expression)=["). append(pointcutDefinition.getPropertyValues().getPropertyValue("expression").getValue()). append("]>").toString(); }
private String buildDescription(BeanReference adviceReference, BeanReference pointcutReference) { return new StringBuilder("Advisor <advice(ref)='"). append(adviceReference.getBeanName()).append("', pointcut(ref)='"). append(pointcutReference.getBeanName()).append("'>").toString(); }
@Test public void testAspectEvent() throws Exception { this.reader.loadBeanDefinitions(CONTEXT); ComponentDefinition[] componentDefinitions = this.eventListener.getComponentDefinitions(); assertEquals("Incorrect number of events fired", 5, componentDefinitions.length); assertTrue("No holder with nested components", componentDefinitions[0] instanceof CompositeComponentDefinition); CompositeComponentDefinition compositeDef = (CompositeComponentDefinition) componentDefinitions[0]; assertEquals("aop:config", compositeDef.getName()); ComponentDefinition[] nestedComponentDefs = compositeDef.getNestedComponents(); assertEquals("Incorrect number of inner components", 2, nestedComponentDefs.length); AspectComponentDefinition acd = null; for (int i = 0; i < nestedComponentDefs.length; i++) { ComponentDefinition componentDefinition = nestedComponentDefs[i]; if (componentDefinition instanceof AspectComponentDefinition) { acd = (AspectComponentDefinition) componentDefinition; break; } } assertNotNull("AspectComponentDefinition not found", acd); BeanDefinition[] beanDefinitions = acd.getBeanDefinitions(); assertEquals(5, beanDefinitions.length); BeanReference[] beanReferences = acd.getBeanReferences(); assertEquals(6, beanReferences.length); Set<String> expectedReferences = new HashSet<String>(); expectedReferences.add("pc"); expectedReferences.add("countingAdvice"); for (int i = 0; i < beanReferences.length; i++) { BeanReference beanReference = beanReferences[i]; expectedReferences.remove(beanReference.getBeanName()); } assertEquals("Incorrect references found", 0, expectedReferences.size()); for (int i = 1; i < componentDefinitions.length; i++) { assertTrue(componentDefinitions[i] instanceof BeanComponentDefinition); } ComponentDefinition[] nestedComponentDefs2 = acd.getNestedComponents(); assertEquals("Inner PointcutComponentDefinition not found", 1, nestedComponentDefs2.length); assertTrue(nestedComponentDefs2[0] instanceof PointcutComponentDefinition); PointcutComponentDefinition pcd = (PointcutComponentDefinition) nestedComponentDefs2[0]; assertEquals("Incorrect number of BeanDefinitions", 1, pcd.getBeanDefinitions().length); }