protected void processConfigurationClass(ConfigurationClass configClass) throws IOException { AnnotationMetadata metadata = configClass.getMetadata(); if (this.environment != null && ProfileHelper.isProfileAnnotationPresent(metadata)) { if (!this.environment.acceptsProfiles(ProfileHelper.getCandidateProfiles(metadata))) { return; } } while (metadata != null) { doProcessConfigurationClass(configClass, metadata); String superClassName = metadata.getSuperClassName(); if (superClassName != null && !Object.class.getName().equals(superClassName)) { if (metadata instanceof StandardAnnotationMetadata) { Class<?> clazz = ((StandardAnnotationMetadata) metadata).getIntrospectedClass(); metadata = new StandardAnnotationMetadata(clazz.getSuperclass()); } else { MetadataReader reader = this.metadataReaderFactory.getMetadataReader(superClassName); metadata = reader.getAnnotationMetadata(); } } else { metadata = null; } } if (this.configurationClasses.contains(configClass) && configClass.getBeanName() != null) { // Explicit bean definition found, probably replacing an import. // Let's remove the old one and go with the new one. this.configurationClasses.remove(configClass); } this.configurationClasses.add(configClass); }
@Override public String[] selectImports(AnnotationMetadata metadata) { try { AnnotationAttributes attributes = AnnotationAttributes.fromMap( metadata.getAnnotationAttributes(EnableAutoConfiguration.class.getName(), true)); Assert.notNull( attributes, "No auto-configuration attributes found. Is " + metadata.getClassName() + " annotated with @EnableAutoConfiguration?"); // Find all possible auto configuration classes, filtering duplicates List<String> factories = new ArrayList<String>( new LinkedHashSet<String>( SpringFactoriesLoader.loadFactoryNames( EnableAutoConfiguration.class, this.beanClassLoader))); // Remove those specifically excluded Set<String> excluded = new LinkedHashSet<String>(); excluded.addAll(Arrays.asList(attributes.getStringArray("exclude"))); excluded.addAll(Arrays.asList(attributes.getStringArray("excludeName"))); factories.removeAll(excluded); ConditionEvaluationReport.get(this.beanFactory).recordExclusions(excluded); // Sort factories = new AutoConfigurationSorter(this.resourceLoader).getInPriorityOrder(factories); return factories.toArray(new String[factories.size()]); } catch (IOException ex) { throw new IllegalStateException(ex); } }
private void processImport( ConfigurationClass configClass, String[] classesToImport, boolean checkForCircularImports) throws IOException { if (checkForCircularImports && this.importStack.contains(configClass)) { this.problemReporter.error( new CircularImportProblem(configClass, this.importStack, configClass.getMetadata())); } else { this.importStack.push(configClass); AnnotationMetadata importingClassMetadata = configClass.getMetadata(); for (String candidate : classesToImport) { MetadataReader reader = this.metadataReaderFactory.getMetadataReader(candidate); if (new AssignableTypeFilter(ImportSelector.class).match(reader, metadataReaderFactory)) { // the candidate class is an ImportSelector -> delegate to it to determine imports try { ImportSelector selector = BeanUtils.instantiateClass(Class.forName(candidate), ImportSelector.class); ImportSelectorContext context = new ImportSelectorContext(importingClassMetadata, this.registry); processImport(configClass, selector.selectImports(context), false); } catch (ClassNotFoundException ex) { throw new IllegalStateException(ex); } } else { // the candidate class not an ImportSelector -> process it as a @Configuration class this.importStack.registerImport(importingClassMetadata.getClassName(), candidate); processConfigurationClass(new ConfigurationClass(reader, null)); } } this.importStack.pop(); } }
@Override public void setImportMetadata(AnnotationMetadata importMetadata) { AnnotationAttributes annotationAttributes = AnnotationAttributes.fromMap( importMetadata.getAnnotationAttributes(EnableRoleChecking.class.getName())); Assert.notNull( annotationAttributes, "No " + EnableRoleChecking.class.getSimpleName() + " annotation found on '" + importMetadata.getClassName() + "'."); }
@Override public void setImportMetadata(AnnotationMetadata importMetadata) { Map<String, Object> elements = importMetadata.getAnnotationAttributes(EnableHello.class.getName()); String name = (String) elements.get("name"); hello().setName(name); }
@Override public void registerBeanDefinitions(AnnotationMetadata meta, BeanDefinitionRegistry registry) { Map<String, Object> attrs = meta.getAnnotationAttributes(EnableReactor.class.getName()); // Create a root Enivronment if (!registry.containsBeanDefinition(Environment.class.getName())) { BeanDefinitionBuilder envBeanDef = BeanDefinitionBuilder.rootBeanDefinition(Environment.class); String configReaderBean = (String) attrs.get("configurationReader"); if (StringUtils.hasText(configReaderBean)) { envBeanDef.addConstructorArgReference(configReaderBean); } else { String profileName = (String) attrs.get("value"); if (StringUtils.hasText(profileName)) { envBeanDef.addConstructorArgValue(new PropertiesConfigurationReader(profileName)); } } registry.registerBeanDefinition(Environment.class.getName(), envBeanDef.getBeanDefinition()); } // Create a ConsumerBeanPostProcessor if (!registry.containsBeanDefinition(ConsumerBeanPostProcessor.class.getName())) { BeanDefinitionBuilder envBeanDef = BeanDefinitionBuilder.rootBeanDefinition(ConsumerBeanPostProcessor.class); registry.registerBeanDefinition( ConsumerBeanPostProcessor.class.getName(), envBeanDef.getBeanDefinition()); } }
private Map<Class<?>, List<Annotation>> getAnnotations(AnnotationMetadata metadata) { MultiValueMap<Class<?>, Annotation> annotations = new LinkedMultiValueMap<Class<?>, Annotation>(); Class<?> source = ClassUtils.resolveClassName(metadata.getClassName(), null); collectAnnotations(source, annotations, new HashSet<Class<?>>()); return Collections.unmodifiableMap(annotations); }
private void processFeatureAnnotations(AnnotationMetadata metadata) { try { for (String annotationType : metadata.getAnnotationTypes()) { MetadataReader metadataReader = new SimpleMetadataReaderFactory().getMetadataReader(annotationType); if (metadataReader.getAnnotationMetadata().isAnnotated(FeatureAnnotation.class.getName())) { Map<String, Object> annotationAttributes = metadataReader .getAnnotationMetadata() .getAnnotationAttributes(FeatureAnnotation.class.getName(), true); // TODO SPR-7420: this is where we can catch user-defined types and avoid instantiating // them for STS purposes FeatureAnnotationParser processor = (FeatureAnnotationParser) BeanUtils.instantiateClass( Class.forName((String) annotationAttributes.get("parser"))); FeatureSpecification spec = processor.process(metadata); spec.execute(this.specificationContext); } } } catch (BeanDefinitionParsingException ex) { throw ex; } catch (Exception ex) { // TODO SPR-7420: what exception to throw? throw new RuntimeException(ex); } }
@Override protected Set<String> getExclusions( AnnotationMetadata metadata, AnnotationAttributes attributes) { Set<String> exclusions = new LinkedHashSet<String>(); Class<?> source = ClassUtils.resolveClassName(metadata.getClassName(), null); for (String annotationName : ANNOTATION_NAMES) { AnnotationAttributes merged = AnnotatedElementUtils.getMergedAnnotationAttributes(source, annotationName); Class<?>[] exclude = (merged == null ? null : merged.getClassArray("exclude")); if (exclude != null) { for (Class<?> excludeClass : exclude) { exclusions.add(excludeClass.getName()); } } } for (List<Annotation> annotations : getAnnotations(metadata).values()) { for (Annotation annotation : annotations) { String[] exclude = (String[]) AnnotationUtils.getAnnotationAttributes(annotation, true).get("exclude"); if (!ObjectUtils.isEmpty(exclude)) { exclusions.addAll(Arrays.asList(exclude)); } } } return exclusions; }
void processCommonDefinitionAnnotations(AnnotatedBeanDefinition abd) { AnnotationMetadata metadata = abd.getMetadata(); if (metadata.isAnnotated(Primary.class.getName())) { abd.setPrimary(true); } if (metadata.isAnnotated(Lazy.class.getName())) { abd.setLazyInit(attributesFor(metadata, Lazy.class).getBoolean("value")); } if (metadata.isAnnotated(DependsOn.class.getName())) { abd.setDependsOn(attributesFor(metadata, DependsOn.class).getStringArray("value")); } if (abd instanceof AbstractBeanDefinition) { if (metadata.isAnnotated(Role.class.getName())) { Integer role = attributesFor(metadata, Role.class).getNumber("value"); ((AbstractBeanDefinition) abd).setRole(role); } } }
/* * (non-Javadoc) * @see org.springframework.context.annotation.ImportBeanDefinitionRegistrar#registerBeanDefinitions(org.springframework.core.type.AnnotationMetadata, org.springframework.beans.factory.support.BeanDefinitionRegistry) */ @Override public void registerBeanDefinitions( AnnotationMetadata metadata, BeanDefinitionRegistry registry) { linkBuilderBeanDefinitionRegistrar.registerBeanDefinitions(metadata, registry); Map<String, Object> attributes = metadata.getAnnotationAttributes(EnableHypermediaSupport.class.getName()); Collection<HypermediaType> types = Arrays.asList((HypermediaType[]) attributes.get("type")); for (HypermediaType type : types) { if (JSONPATH_PRESENT) { AbstractBeanDefinition linkDiscovererBeanDefinition = getLinkDiscovererBeanDefinition(type); registerBeanDefinition( new BeanDefinitionHolder( linkDiscovererBeanDefinition, BeanDefinitionReaderUtils.generateBeanName(linkDiscovererBeanDefinition, registry)), registry); } } if (types.contains(HypermediaType.HAL)) { if (JACKSON2_PRESENT) { BeanDefinitionBuilder halQueryMapperBuilder = rootBeanDefinition(ObjectMapper.class); registerSourcedBeanDefinition( halQueryMapperBuilder, metadata, registry, HAL_OBJECT_MAPPER_BEAN_NAME); BeanDefinitionBuilder customizerBeanDefinition = rootBeanDefinition(DefaultObjectMapperCustomizer.class); registerSourcedBeanDefinition(customizerBeanDefinition, metadata, registry); BeanDefinitionBuilder builder = rootBeanDefinition(Jackson2ModuleRegisteringBeanPostProcessor.class); registerSourcedBeanDefinition(builder, metadata, registry); } } if (!types.isEmpty()) { BeanDefinitionBuilder linkDiscoverersRegistryBuilder = BeanDefinitionBuilder.rootBeanDefinition(PluginRegistryFactoryBean.class); linkDiscoverersRegistryBuilder.addPropertyValue("type", LinkDiscoverer.class); registerSourcedBeanDefinition( linkDiscoverersRegistryBuilder, metadata, registry, LINK_DISCOVERER_REGISTRY_BEAN_NAME); BeanDefinitionBuilder linkDiscoverersBuilder = BeanDefinitionBuilder.rootBeanDefinition(LinkDiscoverers.class); linkDiscoverersBuilder.addConstructorArgReference(LINK_DISCOVERER_REGISTRY_BEAN_NAME); registerSourcedBeanDefinition(linkDiscoverersBuilder, metadata, registry); } registerRelProviderPluginRegistryAndDelegate(registry); }
/** * Determine whether the given class does not match any exclude filter and does match at least one * include filter. * * @param metadataReader the ASM ClassReader for the class * @return whether the class qualifies as a candidate component */ protected boolean isCandidateComponent(MetadataReader metadataReader) throws IOException { for (TypeFilter tf : this.excludeFilters) { if (tf.match(metadataReader, this.metadataReaderFactory)) { return false; } } for (TypeFilter tf : this.includeFilters) { if (tf.match(metadataReader, this.metadataReaderFactory)) { AnnotationMetadata metadata = metadataReader.getAnnotationMetadata(); if (!metadata.isAnnotated(Profile.class.getName())) { return true; } AnnotationAttributes profile = MetadataUtils.attributesFor(metadata, Profile.class); return this.environment.acceptsProfiles(profile.getStringArray("value")); } } return false; }
@Override protected BeanDefinition buildBeanDefinition( AnnotationMetadata importingClassMetadata, Class<? extends Annotation> namedAnnotation) throws Exception { String enableStateMachineEnclosingClassName = importingClassMetadata.getClassName(); // for below classloader, see gh122 Class<?> enableStateMachineEnclosingClass = ClassUtils.forName( enableStateMachineEnclosingClassName, ClassUtils.getDefaultClassLoader()); // return null if it looks like @EnableStateMachine was annotated with class // not extending StateMachineConfigurer. if (!ClassUtils.isAssignable(StateMachineConfigurer.class, enableStateMachineEnclosingClass)) { return null; } BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.rootBeanDefinition(StateMachineDelegatingFactoryBean.class); AnnotationAttributes esmAttributes = AnnotationAttributes.fromMap( importingClassMetadata.getAnnotationAttributes( EnableStateMachine.class.getName(), false)); Boolean contextEvents = esmAttributes.getBoolean("contextEvents"); // check if Scope annotation is defined and set scope from it AnnotationAttributes scopeAttributes = AnnotationAttributes.fromMap( importingClassMetadata.getAnnotationAttributes(Scope.class.getName(), false)); if (scopeAttributes != null) { String scope = scopeAttributes.getAliasedString("value", Scope.class, enableStateMachineEnclosingClass); if (StringUtils.hasText(scope)) { beanDefinitionBuilder.setScope(scope); } } beanDefinitionBuilder.addConstructorArgValue(builder); beanDefinitionBuilder.addConstructorArgValue(StateMachine.class); beanDefinitionBuilder.addConstructorArgValue(importingClassMetadata.getClassName()); beanDefinitionBuilder.addConstructorArgValue(contextEvents); return beanDefinitionBuilder.getBeanDefinition(); }
private Set<String> getPackagesToScan(AnnotationMetadata metadata) { AnnotationAttributes attributes = AnnotationAttributes.fromMap( metadata.getAnnotationAttributes(EntityScan.class.getName())); String[] basePackages = attributes.getAliasedStringArray( "basePackages", EntityScan.class, metadata.getClassName()); Class<?>[] basePackageClasses = attributes.getClassArray("basePackageClasses"); Set<String> packagesToScan = new LinkedHashSet<String>(); packagesToScan.addAll(Arrays.asList(basePackages)); for (Class<?> basePackageClass : basePackageClasses) { packagesToScan.add(ClassUtils.getPackageName(basePackageClass)); } if (packagesToScan.isEmpty()) { String packageName = ClassUtils.getPackageName(metadata.getClassName()); Assert.state( !StringUtils.isEmpty(packageName), "@EntityScan cannot be used with the default package"); return Collections.singleton(packageName); } return packagesToScan; }
/** * Check whether the given bean definition is a candidate for a configuration class, and mark it * accordingly. * * @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) { AnnotationMetadata metadata = null; // Check already loaded Class if present... // since we possibly can't even load the class file for this Class. if (beanDef instanceof AbstractBeanDefinition && ((AbstractBeanDefinition) beanDef).hasBeanClass()) { metadata = new StandardAnnotationMetadata(((AbstractBeanDefinition) beanDef).getBeanClass()); } else { String className = beanDef.getBeanClassName(); if (className != null) { try { MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(className); metadata = metadataReader.getAnnotationMetadata(); } catch (IOException ex) { if (logger.isDebugEnabled()) { logger.debug( "Could not find class file for introspecting factory methods: " + className, ex); } return false; } } } if (metadata != null) { if (metadata.isAnnotated(Configuration.class.getName())) { beanDef.setAttribute(CONFIGURATION_CLASS_ATTRIBUTE, CONFIGURATION_CLASS_FULL); return true; } else if (metadata.isAnnotated(Component.class.getName()) || metadata.hasAnnotatedMethods(Bean.class.getName())) { beanDef.setAttribute(CONFIGURATION_CLASS_ATTRIBUTE, CONFIGURATION_CLASS_LITE); return true; } } return false; }
/** * Derive a bean name from one of the annotations on the class. * * @param annotatedDef the annotation-aware bean definition * @return the bean name, or <code>null</code> if none is found */ protected String determineBeanNameFromAnnotation(AnnotatedBeanDefinition annotatedDef) { AnnotationMetadata amd = annotatedDef.getMetadata(); Set<String> types = amd.getAnnotationTypes(); String beanName = null; for (String type : types) { Map<String, Object> attributes = amd.getAnnotationAttributes(type); if (isStereotypeWithNameValue(type, amd.getMetaAnnotationTypes(type), attributes)) { String value = (String) attributes.get("value"); if (StringUtils.hasLength(value)) { if (beanName != null && !value.equals(beanName)) { throw new IllegalStateException( "Stereotype annotations suggest inconsistent " + "component names: '" + beanName + "' versus '" + value + "'"); } beanName = value; } } } return beanName; }
public void setImportMetadata(AnnotationMetadata importMetadata) { Map<String, Object> enableAttrMap = importMetadata.getAnnotationAttributes(EnableHazelcastHttpSession.class.getName()); AnnotationAttributes enableAttrs = AnnotationAttributes.fromMap(enableAttrMap); if (enableAttrs == null) { // search parent classes Class<?> currentClass = ClassUtils.resolveClassName(importMetadata.getClassName(), beanClassLoader); for (Class<?> classToInspect = currentClass; classToInspect != null; classToInspect = classToInspect.getSuperclass()) { EnableHazelcastHttpSession enableHazelcastHttpSessionAnnotation = AnnotationUtils.findAnnotation(classToInspect, EnableHazelcastHttpSession.class); if (enableHazelcastHttpSessionAnnotation == null) { continue; } enableAttrMap = AnnotationUtils.getAnnotationAttributes(enableHazelcastHttpSessionAnnotation); enableAttrs = AnnotationAttributes.fromMap(enableAttrMap); } } transferAnnotationAttributes(enableAttrs); }
public void registerBeanDefinitions( AnnotationMetadata annotationMetadata, BeanDefinitionRegistry registry) { Map<String, Object> annotationAttributes = annotationMetadata.getAnnotationAttributes(EnableJdbcConnectionRepository.class.getName()); if (annotationAttributes == null) { return; } AnnotationAttributes attributes = new AnnotationAttributes(annotationAttributes); String connectionRepositoryId = attributes.getString("connectionRepositoryId"); String usersConnectionRepositoryId = attributes.getString("usersConnectionRepositoryId"); String connectionFactoryLocatorRef = attributes.getString("connectionFactoryLocatorRef"); String dataSourceRef = attributes.getString("dataSourceRef"); String encryptorRef = attributes.getString("encryptorRef"); String userIdSourceRef = attributes.getString("userIdSourceRef"); registerJdbcConnectionRepositoryBeans( registry, connectionRepositoryId, usersConnectionRepositoryId, connectionFactoryLocatorRef, dataSourceRef, encryptorRef, userIdSourceRef); }
protected void doProcessConfigurationClass( ConfigurationClass configClass, AnnotationMetadata metadata) throws IOException { // recursively process any member (nested) classes first for (String memberClassName : metadata.getMemberClassNames()) { MetadataReader reader = this.metadataReaderFactory.getMetadataReader(memberClassName); AnnotationMetadata memberClassMetadata = reader.getAnnotationMetadata(); if (isConfigurationCandidate(memberClassMetadata)) { processConfigurationClass(new ConfigurationClass(reader, null)); } } // process any @PropertySource annotations Map<String, Object> propertySourceAttributes = metadata.getAnnotationAttributes( org.springframework.context.annotation.PropertySource.class.getName()); if (propertySourceAttributes != null) { String name = (String) propertySourceAttributes.get("name"); String[] locations = (String[]) propertySourceAttributes.get("value"); ClassLoader classLoader = this.resourceLoader.getClassLoader(); for (String location : locations) { location = this.environment.resolveRequiredPlaceholders(location); ResourcePropertySource ps = StringUtils.hasText(name) ? new ResourcePropertySource(name, location, classLoader) : new ResourcePropertySource(location, classLoader); this.propertySources.push(ps); } } // process any @ComponentScan annotions Map<String, Object> componentScanAttributes = metadata.getAnnotationAttributes(ComponentScan.class.getName()); if (componentScanAttributes != null) { // the config class is annotated with @ComponentScan -> perform the scan immediately Set<BeanDefinitionHolder> scannedBeanDefinitions = this.componentScanParser.parse(componentScanAttributes); // 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(), metadataReaderFactory)) { try { this.parse(holder.getBeanDefinition().getBeanClassName(), holder.getBeanName()); } catch (ConflictingBeanDefinitionException ex) { throw new CircularComponentScanException( "A conflicting bean definition was detected while processing @ComponentScan annotations. " + "This usually indicates a circle between scanned packages.", ex); } } } } // process any @Import annotations List<Map<String, Object>> allImportAttribs = AnnotationUtils.findAllAnnotationAttributes(Import.class, metadata.getClassName(), true); for (Map<String, Object> importAttribs : allImportAttribs) { processImport(configClass, (String[]) importAttribs.get("value"), true); } // process any @ImportResource annotations if (metadata.isAnnotated(ImportResource.class.getName())) { String[] resources = (String[]) metadata.getAnnotationAttributes(ImportResource.class.getName()).get("value"); Class<?> readerClass = (Class<?>) metadata.getAnnotationAttributes(ImportResource.class.getName()).get("reader"); if (readerClass == null) { throw new IllegalStateException( "No reader class associated with imported resources: " + StringUtils.arrayToCommaDelimitedString(resources)); } for (String resource : resources) { configClass.addImportedResource(resource, readerClass); } } // process individual @Bean methods Set<MethodMetadata> beanMethods = metadata.getAnnotatedMethods(Bean.class.getName()); for (MethodMetadata methodMetadata : beanMethods) { configClass.addBeanMethod(new BeanMethod(methodMetadata, configClass)); } }
public static AnnotationAttributes attributesFor( AnnotationMetadata metadata, String annoClassName) { return AnnotationAttributes.fromMap(metadata.getAnnotationAttributes(annoClassName, false)); }