@Test public void testQualifiedByParentValue() { StaticApplicationContext parent = new StaticApplicationContext(); GenericBeanDefinition parentLarry = new GenericBeanDefinition(); parentLarry.setBeanClass(Person.class); parentLarry.getPropertyValues().add("name", "ParentLarry"); parentLarry.addQualifier(new AutowireCandidateQualifier(Qualifier.class, "parentLarry")); parent.registerBeanDefinition("someLarry", parentLarry); GenericBeanDefinition otherLarry = new GenericBeanDefinition(); otherLarry.setBeanClass(Person.class); otherLarry.getPropertyValues().add("name", "OtherLarry"); otherLarry.addQualifier(new AutowireCandidateQualifier(Qualifier.class, "otherLarry")); parent.registerBeanDefinition("someOtherLarry", otherLarry); parent.refresh(); StaticApplicationContext context = new StaticApplicationContext(parent); BeanDefinitionReader reader = new XmlBeanDefinitionReader(context); reader.loadBeanDefinitions(CONFIG_LOCATION); context.registerSingleton("testBean", QualifiedByParentValueTestBean.class); context.refresh(); QualifiedByParentValueTestBean testBean = (QualifiedByParentValueTestBean) context.getBean("testBean"); Person person = testBean.getLarry(); assertEquals("ParentLarry", person.getName()); }
@Test public void testQualifiedByAttributesWithCustomQualifierRegistered() { StaticApplicationContext context = new StaticApplicationContext(); BeanDefinitionReader reader = new XmlBeanDefinitionReader(context); reader.loadBeanDefinitions(CONFIG_LOCATION); QualifierAnnotationAutowireCandidateResolver resolver = (QualifierAnnotationAutowireCandidateResolver) context.getDefaultListableBeanFactory().getAutowireCandidateResolver(); resolver.addQualifierType(MultipleAttributeQualifier.class); context.registerSingleton("testBean", MultiQualifierClient.class); context.refresh(); MultiQualifierClient testBean = (MultiQualifierClient) context.getBean("testBean"); assertNotNull( testBean.factoryTheta); assertNotNull( testBean.implTheta); }
@Test @SuppressWarnings("deprecation") public void configureExporterParametersWithEncodingFromPropertiesFile() throws Exception { GenericWebApplicationContext ac = new GenericWebApplicationContext(); ac.setServletContext(new MockServletContext()); BeanDefinitionReader reader = new PropertiesBeanDefinitionReader(ac); reader.loadBeanDefinitions(new ClassPathResource("view.properties", getClass())); ac.refresh(); AbstractJasperReportsView view = (AbstractJasperReportsView) ac.getBean("report"); String encoding = (String) view.getConvertedExporterParameters().get( net.sf.jasperreports.engine.export.JRHtmlExporterParameter.CHARACTER_ENCODING); assertEquals("UTF-8", encoding); request.setAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, ac); view.render(getModel(), request, response); assertEquals("Response content type is incorrect", "text/html;charset=UTF-8", response.getContentType()); }
private void loadBeanDefinitionsFromImportedResources(final Map<String, Class<? extends BeanDefinitionReader>> importedResources) { final Map<Class<?>, BeanDefinitionReader> readerInstanceCache = new HashMap<Class<?>, BeanDefinitionReader>(); for (final Map.Entry<String, Class<? extends BeanDefinitionReader>> entry : importedResources.entrySet()) { final String resource = entry.getKey(); final Class<? extends BeanDefinitionReader> readerClass = entry.getValue(); if (!readerInstanceCache.containsKey(readerClass)) { try { // Instantiate the specified BeanDefinitionReader final BeanDefinitionReader readerInstance = readerClass.getConstructor(BeanDefinitionRegistry.class).newInstance(this.registry); // Delegate the current ResourceLoader to it if possible if (readerInstance instanceof AbstractBeanDefinitionReader) { final AbstractBeanDefinitionReader abdr = ((AbstractBeanDefinitionReader) readerInstance); abdr.setResourceLoader(this.resourceLoader); abdr.setEnvironment(this.environment); } readerInstanceCache.put(readerClass, readerInstance); } catch (final Exception ex) { throw new IllegalStateException("Could not instantiate BeanDefinitionReader class [" + readerClass.getName() + "]"); } } final BeanDefinitionReader reader = readerInstanceCache.get(readerClass); // TODO SPR-6310: qualify relative path locations as done in AbstractContextLoader.modifyLocations reader.loadBeanDefinitions(resource); } }
private void loadBeanDefinitionsFromImportedResources( Map<String, Class<? extends BeanDefinitionReader>> importedResources) { Map<Class<?>, BeanDefinitionReader> readerInstanceCache = new HashMap<Class<?>, BeanDefinitionReader>(); for (Map.Entry<String, Class<? extends BeanDefinitionReader>> entry : importedResources.entrySet()) { String resource = entry.getKey(); Class<? extends BeanDefinitionReader> readerClass = entry.getValue(); if (!readerInstanceCache.containsKey(readerClass)) { try { // Instantiate the specified BeanDefinitionReader BeanDefinitionReader readerInstance = readerClass.getConstructor(BeanDefinitionRegistry.class).newInstance(this.registry); // Delegate the current ResourceLoader to it if possible if (readerInstance instanceof AbstractBeanDefinitionReader) { AbstractBeanDefinitionReader abdr = ((AbstractBeanDefinitionReader) readerInstance); abdr.setResourceLoader(this.resourceLoader); abdr.setEnvironment(this.environment); } readerInstanceCache.put(readerClass, readerInstance); } catch (Exception ex) { throw new IllegalStateException( "Could not instantiate BeanDefinitionReader class [" + readerClass.getName() + "]"); } } BeanDefinitionReader reader = readerInstanceCache.get(readerClass); // TODO SPR-6310: qualify relative path locations as done in AbstractContextLoader.modifyLocations reader.loadBeanDefinitions(resource); } }
@Test public void testNonQualifiedFieldFails() { StaticApplicationContext context = new StaticApplicationContext(); BeanDefinitionReader reader = new XmlBeanDefinitionReader(context); reader.loadBeanDefinitions(CONFIG_LOCATION); context.registerSingleton("testBean", NonQualifiedTestBean.class); try { context.refresh(); fail("Should have thrown a BeanCreationException"); } catch (BeanCreationException e) { assertTrue(e.getMessage().contains("found 6")); } }
@Test public void testQualifiedByValue() { StaticApplicationContext context = new StaticApplicationContext(); BeanDefinitionReader reader = new XmlBeanDefinitionReader(context); reader.loadBeanDefinitions(CONFIG_LOCATION); context.registerSingleton("testBean", QualifiedByValueTestBean.class); context.refresh(); QualifiedByValueTestBean testBean = (QualifiedByValueTestBean) context.getBean("testBean"); Person person = testBean.getLarry(); assertEquals("Larry", person.getName()); }
@Test public void testQualifiedByBeanName() { StaticApplicationContext context = new StaticApplicationContext(); BeanDefinitionReader reader = new XmlBeanDefinitionReader(context); reader.loadBeanDefinitions(CONFIG_LOCATION); context.registerSingleton("testBean", QualifiedByBeanNameTestBean.class); context.refresh(); QualifiedByBeanNameTestBean testBean = (QualifiedByBeanNameTestBean) context.getBean("testBean"); Person person = testBean.getLarry(); assertEquals("LarryBean", person.getName()); assertTrue(testBean.myProps != null && testBean.myProps.isEmpty()); }
@Test public void testQualifiedByFieldName() { StaticApplicationContext context = new StaticApplicationContext(); BeanDefinitionReader reader = new XmlBeanDefinitionReader(context); reader.loadBeanDefinitions(CONFIG_LOCATION); context.registerSingleton("testBean", QualifiedByFieldNameTestBean.class); context.refresh(); QualifiedByFieldNameTestBean testBean = (QualifiedByFieldNameTestBean) context.getBean("testBean"); Person person = testBean.getLarry(); assertEquals("LarryBean", person.getName()); }
@Test public void testQualifiedByParameterName() { StaticApplicationContext context = new StaticApplicationContext(); BeanDefinitionReader reader = new XmlBeanDefinitionReader(context); reader.loadBeanDefinitions(CONFIG_LOCATION); context.registerSingleton("testBean", QualifiedByParameterNameTestBean.class); context.refresh(); QualifiedByParameterNameTestBean testBean = (QualifiedByParameterNameTestBean) context.getBean("testBean"); Person person = testBean.getLarry(); assertEquals("LarryBean", person.getName()); }
@Test public void testQualifiedByAlias() { StaticApplicationContext context = new StaticApplicationContext(); BeanDefinitionReader reader = new XmlBeanDefinitionReader(context); reader.loadBeanDefinitions(CONFIG_LOCATION); context.registerSingleton("testBean", QualifiedByAliasTestBean.class); context.refresh(); QualifiedByAliasTestBean testBean = (QualifiedByAliasTestBean) context.getBean("testBean"); Person person = testBean.getStooge(); assertEquals("LarryBean", person.getName()); }
@Test public void testQualifiedByAnnotation() { StaticApplicationContext context = new StaticApplicationContext(); BeanDefinitionReader reader = new XmlBeanDefinitionReader(context); reader.loadBeanDefinitions(CONFIG_LOCATION); context.registerSingleton("testBean", QualifiedByAnnotationTestBean.class); context.refresh(); QualifiedByAnnotationTestBean testBean = (QualifiedByAnnotationTestBean) context.getBean("testBean"); Person person = testBean.getLarry(); assertEquals("LarrySpecial", person.getName()); }
@Test public void testQualifiedByCustomValue() { StaticApplicationContext context = new StaticApplicationContext(); BeanDefinitionReader reader = new XmlBeanDefinitionReader(context); reader.loadBeanDefinitions(CONFIG_LOCATION); context.registerSingleton("testBean", QualifiedByCustomValueTestBean.class); context.refresh(); QualifiedByCustomValueTestBean testBean = (QualifiedByCustomValueTestBean) context.getBean("testBean"); Person person = testBean.getCurly(); assertEquals("Curly", person.getName()); }
@Test public void testQualifiedByAnnotationValue() { StaticApplicationContext context = new StaticApplicationContext(); BeanDefinitionReader reader = new XmlBeanDefinitionReader(context); reader.loadBeanDefinitions(CONFIG_LOCATION); context.registerSingleton("testBean", QualifiedByAnnotationValueTestBean.class); context.refresh(); QualifiedByAnnotationValueTestBean testBean = (QualifiedByAnnotationValueTestBean) context.getBean("testBean"); Person person = testBean.getLarry(); assertEquals("LarrySpecial", person.getName()); }
@Test public void testQualifiedByAttributesFailsWithoutCustomQualifierRegistered() { StaticApplicationContext context = new StaticApplicationContext(); BeanDefinitionReader reader = new XmlBeanDefinitionReader(context); reader.loadBeanDefinitions(CONFIG_LOCATION); context.registerSingleton("testBean", QualifiedByAttributesTestBean.class); try { context.refresh(); fail("should have thrown a BeanCreationException"); } catch (BeanCreationException e) { assertTrue(e.getMessage().contains("found 6")); } }
@Test public void testCustomResolver() { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); BeanDefinitionReader reader = new XmlBeanDefinitionReader(bf); reader.loadBeanDefinitions(CONTEXT); CustomAutowireConfigurer cac = new CustomAutowireConfigurer(); CustomResolver customResolver = new CustomResolver(); bf.setAutowireCandidateResolver(customResolver); cac.postProcessBeanFactory(bf); TestBean testBean = (TestBean) bf.getBean("testBean"); assertEquals("#1!", testBean.getName()); }
public static void addConfigurationFromXmlResource(BeanDefinitionRegistry context, Resource resource, boolean errorOnMissingResource) { BeanDefinitionReader reader = new XmlBeanDefinitionReader(context); if ( !resource.exists() ) { if ( errorOnMissingResource ) { throw new RuntimeException("Resource "+resource.getFilename()+" does not exist"); } else { LOG.info("[Process] Resource "+resource.getFilename()+" does not exist; no bean definitions will be added"); } } else { LOG.info("[Process] Loading bean definitions from resource "+resource.getFilename()); reader.loadBeanDefinitions(resource); } }
public void testConfigureExporterParametersWithEncodingFromPropertiesFile() throws Exception { GenericWebApplicationContext ac = new GenericWebApplicationContext(); ac.setServletContext(new MockServletContext()); BeanDefinitionReader reader = new PropertiesBeanDefinitionReader(ac); reader.loadBeanDefinitions(new ClassPathResource("view.properties", getClass())); ac.refresh(); AbstractJasperReportsView view = (AbstractJasperReportsView) ac.getBean("report"); String encoding = (String) view.getConvertedExporterParameters().get(JRHtmlExporterParameter.CHARACTER_ENCODING); assertEquals("UTF-8", encoding); request.setAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, ac); view.render(getModel(), request, response); assertEquals("Response content type is incorrect", "text/html;charset=UTF-8", response.getContentType()); }
private XmlBeanDefinationScannerAgent(BeanDefinitionReader reader) { this.reader = reader; if (SpringPlugin.basePackagePrefixes != null && !basePackageInited) { ClassPathBeanDefinitionScannerAgent xmlBeanDefinitionScannerAgent = ClassPathBeanDefinitionScannerAgent.getInstance(new ClassPathBeanDefinitionScanner(reader.getRegistry())); for (String basePackage : SpringPlugin.basePackagePrefixes) { xmlBeanDefinitionScannerAgent.registerBasePackage(basePackage); } basePackageInited = true; } }
/** * Apply processing and build a complete {@link ConfigurationClass} by reading the * annotations, members and methods from the source class. This method can be called * multiple times as relevant sources are discovered. * @param configClass the configuration class being build * @param sourceClass a source class * @return the superclass, {@code null} if none found or previously processed */ protected final SourceClass doProcessConfigurationClass(ConfigurationClass configClass, SourceClass sourceClass) throws IOException { // recursively process any member (nested) classes first processMemberClasses(configClass, sourceClass); // process any @PropertySource annotations for (AnnotationAttributes propertySource : AnnotationConfigUtils.attributesForRepeatable( sourceClass.getMetadata(), PropertySources.class, org.springframework.context.annotation.PropertySource.class)) { processPropertySource(propertySource); } // process any @ComponentScan annotations AnnotationAttributes componentScan = AnnotationConfigUtils.attributesFor(sourceClass.getMetadata(), ComponentScan.class); if (componentScan != null) { // the config class is annotated with @ComponentScan -> perform the scan immediately if (!this.conditionEvaluator.shouldSkip(sourceClass.getMetadata(), ConfigurationPhase.REGISTER_BEAN)) { Set<BeanDefinitionHolder> scannedBeanDefinitions = this.componentScanParser.parse(componentScan, sourceClass.getMetadata().getClassName()); // check the set of scanned definitions for any further config classes and parse recursively if necessary for (BeanDefinitionHolder holder : scannedBeanDefinitions) { if (ConfigurationClassUtils.checkConfigurationClassCandidate(holder.getBeanDefinition(), this.metadataReaderFactory)) { parse(holder.getBeanDefinition().getBeanClassName(), holder.getBeanName()); } } } } // process any @Import annotations processImports(configClass, sourceClass, getImports(sourceClass), true); // process any @ImportResource annotations if (sourceClass.getMetadata().isAnnotated(ImportResource.class.getName())) { AnnotationAttributes importResource = AnnotationConfigUtils.attributesFor(sourceClass.getMetadata(), ImportResource.class); String[] resources = importResource.getStringArray("value"); Class<? extends BeanDefinitionReader> readerClass = importResource.getClass("reader"); for (String resource : resources) { String resolvedResource = this.environment.resolveRequiredPlaceholders(resource); configClass.addImportedResource(resolvedResource, readerClass); } } // process individual @Bean methods Set<MethodMetadata> beanMethods = sourceClass.getMetadata().getAnnotatedMethods(Bean.class.getName()); for (MethodMetadata methodMetadata : beanMethods) { configClass.addBeanMethod(new BeanMethod(methodMetadata, configClass)); } // process superclass, if any if (sourceClass.getMetadata().hasSuperClass()) { String superclass = sourceClass.getMetadata().getSuperClassName(); if (!superclass.startsWith("java") && !this.knownSuperclasses.containsKey(superclass)) { this.knownSuperclasses.put(superclass, configClass); // superclass found, return its annotation metadata and recurse try { return sourceClass.getSuperClass(); } catch (ClassNotFoundException ex) { throw new IllegalStateException(ex); } } } // no superclass, processing is complete return null; }
public void addImportedResource(String importedResource, Class<? extends BeanDefinitionReader> readerClass) { this.importedResources.put(importedResource, readerClass); }
public Map<String, Class<? extends BeanDefinitionReader>> getImportedResources() { return this.importedResources; }
@Override protected BeanDefinitionReader createBeanDefinitionReader( GenericApplicationContext context) { return new GroovyBeanDefinitionReader(context); }
private void loadBeanDefinitionsFromImportedResources( Map<String, Class<? extends BeanDefinitionReader>> importedResources) { Map<Class<?>, BeanDefinitionReader> readerInstanceCache = new HashMap<Class<?>, BeanDefinitionReader>(); for (Map.Entry<String, Class<? extends BeanDefinitionReader>> entry : importedResources.entrySet()) { String resource = entry.getKey(); Class<? extends BeanDefinitionReader> readerClass = entry.getValue(); // Default reader selection necessary? if (BeanDefinitionReader.class == readerClass) { if (StringUtils.endsWithIgnoreCase(resource, ".groovy")) { // When clearly asking for Groovy, that's what they'll get... readerClass = GroovyBeanDefinitionReader.class; } else { // Primarily ".xml" files but for any other extension as well readerClass = XmlBeanDefinitionReader.class; } } BeanDefinitionReader reader = readerInstanceCache.get(readerClass); if (reader == null) { try { // Instantiate the specified BeanDefinitionReader reader = readerClass.getConstructor(BeanDefinitionRegistry.class).newInstance(this.registry); // Delegate the current ResourceLoader to it if possible if (reader instanceof AbstractBeanDefinitionReader) { AbstractBeanDefinitionReader abdr = ((AbstractBeanDefinitionReader) reader); abdr.setResourceLoader(this.resourceLoader); abdr.setEnvironment(this.environment); } readerInstanceCache.put(readerClass, reader); } catch (Exception ex) { throw new IllegalStateException( "Could not instantiate BeanDefinitionReader class [" + readerClass.getName() + "]"); } } // TODO SPR-6310: qualify relative path locations as done in AbstractContextLoader.modifyLocations reader.loadBeanDefinitions(resource); } }