Java Code Examples for org.springframework.core.annotation.AnnotationAttributes

The following examples show how to use org.springframework.core.annotation.AnnotationAttributes. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
/**
 * 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} 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) {
		AnnotationAttributes attributes = AnnotationConfigUtils.attributesFor(amd, type);
		if (isStereotypeWithNameValue(type, amd.getMetaAnnotationTypes(type), attributes)) {
			Object value = attributes.get("value");
			if (value instanceof String) {
				String strVal = (String) value;
				if (StringUtils.hasLength(strVal)) {
					if (beanName != null && !strVal.equals(beanName)) {
						throw new IllegalStateException("Stereotype annotations suggest inconsistent " +
								"component names: '" + beanName + "' versus '" + strVal + "'");
					}
					beanName = strVal;
				}
			}
		}
	}
	return beanName;
}
 
Example 2
Source Project: onetwo   Source File: EnableJFishCloudExtensionSelector.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected List<String> doSelect(AnnotationMetadata metadata, AnnotationAttributes attributes) {
	List<String> classNames = new ArrayList<String>();
	
	classNames.add(BootCloudConfigration.class.getName());
	classNames.add(AuthEnvsConfiguration.class.getName());
	classNames.add(ErrorHandleConfiguration.class.getName());
	classNames.add(AccessLogConfiguration.class.getName());
	classNames.add(GraceKillConfiguration.class.getName());
	
	classNames.add(CornerFeignConfiguration.class.getName());
	
	classNames.add(CanaryConfiguration.class.getName());
	
	classNames.add(ConfigClientConfiguration.class.getName());
	
	//sleuth
	classNames.add(SleuthConfiguration.class.getName());
	
	classNames.add(CloudManagementConfiguration.class.getName());
	
	return classNames;
}
 
Example 3
Source Project: conf4j   Source File: ConfigurationTypeRegistrar.java    License: MIT License 6 votes vote down vote up
private void registerConfigurationType(BeanDefinitionRegistry registry, AnnotationAttributes attributes) {
    Class<?> configurationType = attributes.getClass("value");
    String[] names = attributes.getStringArray("name");

    BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(configurationType);
    addConf4jConfigurationIndicator(builder.getRawBeanDefinition(), ConfigurationIndicator.MANUAL);

    String beanName;
    String[] aliases = null;
    if (names.length == 0) {
        beanName = configurationType.getName();
    } else if (names.length == 1) {
        beanName = names[0];
    } else {
        beanName = names[0];
        aliases = ArrayUtils.subarray(names, 1, names.length);
    }

    registry.registerBeanDefinition(beanName, builder.getBeanDefinition());
    if (aliases != null) {
        for (String alias : aliases) {
            registry.registerAlias(beanName, alias);
        }
    }
}
 
Example 4
Source Project: java-technology-stack   Source File: MBeanExportConfiguration.java    License: MIT License 6 votes vote down vote up
private void setupServer(AnnotationMBeanExporter exporter, AnnotationAttributes enableMBeanExport) {
	String server = enableMBeanExport.getString("server");
	if (StringUtils.hasLength(server) && this.environment != null) {
		server = this.environment.resolvePlaceholders(server);
	}
	if (StringUtils.hasText(server)) {
		Assert.state(this.beanFactory != null, "No BeanFactory set");
		exporter.setServer(this.beanFactory.getBean(server, MBeanServer.class));
	}
	else {
		SpecificPlatform specificPlatform = SpecificPlatform.get();
		if (specificPlatform != null) {
			MBeanServer mbeanServer = specificPlatform.getMBeanServer();
			if (mbeanServer != null) {
				exporter.setServer(mbeanServer);
			}
		}
	}
}
 
Example 5
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
    AnnotationAttributes annotationAttributes = AnnotationAttributes.fromMap(importingClassMetadata.getAnnotationAttributes(GRpcClientScan.class.getCanonicalName()));
    if (annotationAttributes == null) {
        log.warn("GrpcScan was not found.Please check your configuration.");
        return;
    }
    ClassPathGRpcServiceScanner classPathGrpcServiceScanner = new ClassPathGRpcServiceScanner(registry, beanFactory);
    classPathGrpcServiceScanner.setResourceLoader(this.resourceLoader);
    classPathGrpcServiceScanner.addIncludeFilter(new AnnotationTypeFilter(GRpcService.class));
    List<String> basePackages = AutoConfigurationPackages.get(this.beanFactory);
    for (String pkg : annotationAttributes.getStringArray("basePackages")) {
        if (StringUtils.hasText(pkg)) {
            basePackages.add(pkg);
        }
    }
    classPathGrpcServiceScanner.doScan(StringUtils.toStringArray(basePackages));
}
 
Example 6
Source Project: java-technology-stack   Source File: AnnotationConfigUtils.java    License: MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
static Set<AnnotationAttributes> attributesForRepeatable(
		AnnotationMetadata metadata, String containerClassName, String annotationClassName) {

	Set<AnnotationAttributes> result = new LinkedHashSet<>();

	// Direct annotation present?
	addAttributesIfNotNull(result, metadata.getAnnotationAttributes(annotationClassName, false));

	// Container annotation present?
	Map<String, Object> container = metadata.getAnnotationAttributes(containerClassName, false);
	if (container != null && container.containsKey("value")) {
		for (Map<String, Object> containedAttributes : (Map<String, Object>[]) container.get("value")) {
			addAttributesIfNotNull(result, containedAttributes);
		}
	}

	// Return merged result
	return Collections.unmodifiableSet(result);
}
 
Example 7
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata,
		BeanDefinitionRegistry registry) {
	AnnotationAttributes annotationAttributes = AnnotationAttributes
			.fromMap(importingClassMetadata.getAnnotationAttributes(
					EnableContextRegion.class.getName(), false));
	Assert.notNull(annotationAttributes,
			"@EnableRegionProvider is not present on importing class "
					+ importingClassMetadata.getClassName());

	boolean autoDetect = annotationAttributes.getBoolean("autoDetect");
	boolean useDefaultAwsRegionChain = annotationAttributes
			.getBoolean("useDefaultAwsRegionChain");
	String configuredRegion = annotationAttributes.getString("region");

	registerRegionProvider(registry, autoDetect, useDefaultAwsRegionChain,
			configuredRegion);
}
 
Example 8
/**
 * Register, escalate, and configure the AspectJ auto proxy creator based on the value
 * of the @{@link EnableAspectJAutoProxy#proxyTargetClass()} attribute on the importing
 * {@code @Configuration} class.
 */
@Override
public void registerBeanDefinitions(
		AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {

	AopConfigUtils.registerAspectJAnnotationAutoProxyCreatorIfNecessary(registry);

	AnnotationAttributes enableAspectJAutoProxy =
			AnnotationConfigUtils.attributesFor(importingClassMetadata, EnableAspectJAutoProxy.class);
	if (enableAspectJAutoProxy.getBoolean("proxyTargetClass")) {
		AopConfigUtils.forceAutoProxyCreatorToUseClassProxying(registry);
	}
	if (enableAspectJAutoProxy.getBoolean("exposeProxy")) {
		AopConfigUtils.forceAutoProxyCreatorToExposeProxy(registry);
	}
}
 
Example 9
@Override
public ScopeMetadata resolveScopeMetadata(BeanDefinition definition) {
	ScopeMetadata metadata = new ScopeMetadata();
	if (definition instanceof AnnotatedBeanDefinition) {
		AnnotatedBeanDefinition annDef = (AnnotatedBeanDefinition) definition;
		AnnotationAttributes attributes = AnnotationConfigUtils.attributesFor(annDef.getMetadata(), this.scopeAnnotationType);
		if (attributes != null) {
			metadata.setScopeName(attributes.getAliasedString("value", this.scopeAnnotationType, definition.getSource()));
			ScopedProxyMode proxyMode = attributes.getEnum("proxyMode");
			if (proxyMode == null || proxyMode == ScopedProxyMode.DEFAULT) {
				proxyMode = this.defaultProxyMode;
			}
			metadata.setScopedProxyMode(proxyMode);
		}
	}
	return metadata;
}
 
Example 10
@SuppressWarnings("unchecked")
private <T extends Collection<AnnotationAttributes>> T toAnnotationAttributesFromMultiValueMap(
		MultiValueMap<String, Object> map) {

	List<AnnotationAttributes> annotationAttributesList = new ArrayList<>();

	map.forEach((key, value) -> {
		for (int index = 0, size = value.size(); index < size; index++) {

			AnnotationAttributes annotationAttributes =
				resolveAnnotationAttributes(annotationAttributesList, index);

			annotationAttributes.put(key, value.get(index));
		}
	});

	return (T) annotationAttributesList;
}
 
Example 11
Source Project: java-technology-stack   Source File: BeanAnnotationHelper.java    License: MIT License 6 votes vote down vote up
public static String determineBeanNameFor(Method beanMethod) {
	String beanName = beanNameCache.get(beanMethod);
	if (beanName == null) {
		// By default, the bean name is the name of the @Bean-annotated method
		beanName = beanMethod.getName();
		// Check to see if the user has explicitly set a custom bean name...
		AnnotationAttributes bean =
				AnnotatedElementUtils.findMergedAnnotationAttributes(beanMethod, Bean.class, false, false);
		if (bean != null) {
			String[] names = bean.getStringArray("name");
			if (names.length > 0) {
				beanName = names[0];
			}
		}
		beanNameCache.put(beanMethod, beanName);
	}
	return beanName;
}
 
Example 12
@Test
public void overriddenContextConfigurationValue() throws Exception {
	Class<?> declaringClass = OverriddenMetaValueConfigTestCase.class;
	AnnotationDescriptor<ContextConfiguration> descriptor = findAnnotationDescriptor(declaringClass,
		ContextConfiguration.class);
	assertNotNull(descriptor);
	assertEquals(declaringClass, descriptor.getRootDeclaringClass());
	assertEquals(MetaValueConfig.class, descriptor.getComposedAnnotationType());
	assertEquals(ContextConfiguration.class, descriptor.getAnnotationType());
	assertNotNull(descriptor.getComposedAnnotation());
	assertEquals(MetaValueConfig.class, descriptor.getComposedAnnotationType());

	// direct access to annotation value:
	assertArrayEquals(new String[] { "foo.xml" }, descriptor.getAnnotation().value());

	// overridden attribute:
	AnnotationAttributes attributes = descriptor.getAnnotationAttributes();

	// NOTE: we would like to be able to override the 'value' attribute; however,
	// Spring currently does not allow overrides for the 'value' attribute.
	// See SPR-11393 for related discussions.
	assertArrayEquals(new String[] { "foo.xml" }, attributes.getStringArray("value"));
}
 
Example 13
Source Project: onetwo   Source File: MvcInterceptorManager.java    License: Apache License 2.0 6 votes vote down vote up
/***
 * 直接查找Interceptor
 * @author wayshall
 * @param hm
 * @return
 */
final protected Collection<AnnotationAttributes> findInterceptorAnnotationAttrsList(HandlerMethod hm){
	Set<Interceptor> inters = AnnotatedElementUtils.getMergedRepeatableAnnotations(hm.getMethod(), Interceptor.class);
	if(LangUtils.isEmpty(inters)){
		inters = AnnotatedElementUtils.getMergedRepeatableAnnotations(hm.getBeanType(), Interceptor.class);
	}
	if(LangUtils.isEmpty(inters)){
		return Collections.emptyList();
	}
	Collection<AnnotationAttributes> attrs = inters.stream()
													.map(inter->org.springframework.core.annotation.AnnotationUtils.getAnnotationAttributes(null, inter))
													.collect(Collectors.toSet());
	boolean hasDisabledFlag = attrs.stream()
									.anyMatch(attr->asMvcInterceptorMeta(attr).getInterceptorType()==DisableMvcInterceptor.class);
	if(hasDisabledFlag){
		return Collections.emptyList();
	}
	return attrs;
}
 
Example 14
/**
 * This implementation resolves the type of annotation from generic metadata and
 * validates that (a) the annotation is in fact present on the importing
 * {@code @Configuration} class and (b) that the given annotation has an
 * {@linkplain #getAdviceModeAttributeName() advice mode attribute} of type
 * {@link AdviceMode}.
 * <p>The {@link #selectImports(AdviceMode)} method is then invoked, allowing the
 * concrete implementation to choose imports in a safe and convenient fashion.
 * @throws IllegalArgumentException if expected annotation {@code A} is not present
 * on the importing {@code @Configuration} class or if {@link #selectImports(AdviceMode)}
 * returns {@code null}
 */
@Override
public final String[] selectImports(AnnotationMetadata importingClassMetadata) {
	Class<?> annoType = GenericTypeResolver.resolveTypeArgument(getClass(), AdviceModeImportSelector.class);
	AnnotationAttributes attributes = AnnotationConfigUtils.attributesFor(importingClassMetadata, annoType);
	if (attributes == null) {
		throw new IllegalArgumentException(String.format(
			"@%s is not present on importing class '%s' as expected",
			annoType.getSimpleName(), importingClassMetadata.getClassName()));
	}

	AdviceMode adviceMode = attributes.getEnum(this.getAdviceModeAttributeName());
	String[] imports = selectImports(adviceMode);
	if (imports == null) {
		throw new IllegalArgumentException(String.format("Unknown AdviceMode: '%s'", adviceMode));
	}
	return imports;
}
 
Example 15
Source Project: easy-rabbitmq   Source File: ProducerRegistrar.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void registerBeanDefinitions(AnnotationMetadata metadata,
    BeanDefinitionRegistry registry) {

  AnnotationAttributes attributes =
      AnnotationAttributes.fromMap(metadata.getAnnotationAttributes(RqueueScan.class.getName()));
  if (attributes == null) {
    log.warn("No @RqueueScan was found");
    return;
  }

  String[] basePackages = attributes.getStringArray("value");
  String basePackage = metadata.getClassName()
      .substring(0, metadata.getClassName().lastIndexOf("."));
  if (basePackages.length == 0) {
    basePackages = new String[]{basePackage};
  } else {
    basePackages = Arrays.copyOf(basePackages, basePackages.length + 1);
    basePackages[basePackages.length - 1] = basePackage;
  }

  ProducerScanner scanner = new ProducerScanner(registry);
  scanner.setResourceLoader(resourceLoader);
  scanner.scan(basePackages);
}
 
Example 16
Source Project: faster-framework-project   Source File: GRpcApiRegister.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
    AnnotationAttributes annotationAttributes = AnnotationAttributes.fromMap(importingClassMetadata.getAnnotationAttributes(GRpcServerScan.class.getCanonicalName()));
    if (annotationAttributes == null) {
        log.warn("GrpcScan was not found.Please check your configuration.");
        return;
    }
    ClassPathBeanDefinitionScanner classPathGrpcApiScanner = new ClassPathBeanDefinitionScanner(registry, false);
    classPathGrpcApiScanner.setResourceLoader(this.resourceLoader);
    classPathGrpcApiScanner.addIncludeFilter(new AnnotationTypeFilter(GRpcApi.class));
    List<String> basePackages = AutoConfigurationPackages.get(this.beanFactory);
    for (String pkg : annotationAttributes.getStringArray("basePackages")) {
        if (StringUtils.hasText(pkg)) {
            basePackages.add(pkg);
        }
    }
    classPathGrpcApiScanner.scan(StringUtils.toStringArray(basePackages));
}
 
Example 17
Source Project: java-technology-stack   Source File: AspectJAutoProxyRegistrar.java    License: MIT License 6 votes vote down vote up
/**
 * Register, escalate, and configure the AspectJ auto proxy creator based on the value
 * of the @{@link EnableAspectJAutoProxy#proxyTargetClass()} attribute on the importing
 * {@code @Configuration} class.
 */
@Override
public void registerBeanDefinitions(
		AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {

	AopConfigUtils.registerAspectJAnnotationAutoProxyCreatorIfNecessary(registry);

	AnnotationAttributes enableAspectJAutoProxy =
			AnnotationConfigUtils.attributesFor(importingClassMetadata, EnableAspectJAutoProxy.class);
	if (enableAspectJAutoProxy != null) {
		if (enableAspectJAutoProxy.getBoolean("proxyTargetClass")) {
			AopConfigUtils.forceAutoProxyCreatorToUseClassProxying(registry);
		}
		if (enableAspectJAutoProxy.getBoolean("exposeProxy")) {
			AopConfigUtils.forceAutoProxyCreatorToExposeProxy(registry);
		}
	}
}
 
Example 18
Source Project: synapse   Source File: EventSourceBeanRegistrar.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void registerBeanDefinitions(final String channelName,
                                       final String beanName,
                                       final AnnotationAttributes annotationAttributes,
                                       final BeanDefinitionRegistry registry) {
    final Class<? extends MessageLog> channelSelector = annotationAttributes.getClass("selector");
    final String messageLogBeanName = Objects.toString(
            emptyToNull(annotationAttributes.getString("messageLogReceiverEndpoint")),
            beanNameForMessageLogReceiverEndpoint(channelName));

    if (!registry.containsBeanDefinition(messageLogBeanName)) {
        registerMessageLogBeanDefinition(registry, messageLogBeanName, channelName, channelSelector);
    } else {
        throw new BeanCreationException(messageLogBeanName, format("MessageLogReceiverEndpoint %s is already registered.", messageLogBeanName));
    }
    if (!registry.containsBeanDefinition(beanName)) {
        registerEventSourceBeanDefinition(registry, beanName, messageLogBeanName, channelName, channelSelector);
    } else {
        throw new BeanCreationException(beanName, format("EventSource %s is already registered.", beanName));
    }
}
 
Example 19
Source Project: onetwo   Source File: EnabledKeyCondition.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
	AnnotationAttributes attrubutes = getAnnotationAttributes(metadata);
	
	String mainKey = getMainEnabledKey(context.getEnvironment(), attrubutes);
	if(StringUtils.isNotBlank(mainKey) && !isEnabled(context.getEnvironment(), mainKey)){
		return ConditionOutcome.noMatch("main property ["+mainKey+"] is not enabled");
	}
	
	String key = getEnabledKey(context.getEnvironment(), attrubutes);
	if(!isEnabled(context.getEnvironment(), key)){
		return ConditionOutcome.noMatch("property ["+key+"] is not enabled");
	}
	return ConditionOutcome.match("property ["+key+"] is enabled");
}
 
Example 20
Source Project: onetwo   Source File: MvcInterceptorManager.java    License: Apache License 2.0 5 votes vote down vote up
final protected Collection<AnnotationAttributes> derectFindInterceptorAnnotationAttrsList(HandlerMethod hm){
	//间接包含了@Interceptor的,也能找到……
	Set<Interceptor> inters = AnnotatedElementUtils.getMergedRepeatableAnnotations(hm.getMethod(), Interceptor.class);
	if(LangUtils.isEmpty(inters)){
		inters = AnnotatedElementUtils.getMergedRepeatableAnnotations(hm.getBeanType(), Interceptor.class);
	}
	if(LangUtils.isEmpty(inters)){
		return Collections.emptyList();
	}
	return inters.stream()
				.map(inter->org.springframework.core.annotation.AnnotationUtils.getAnnotationAttributes(null, inter))
				.collect(Collectors.toSet());
}
 
Example 21
Source Project: spring-analysis-note   Source File: AbstractAsyncConfiguration.java    License: MIT License 5 votes vote down vote up
@Override
public void setImportMetadata(AnnotationMetadata importMetadata) {
	this.enableAsync = AnnotationAttributes.fromMap(
			importMetadata.getAnnotationAttributes(EnableAsync.class.getName(), false));
	if (this.enableAsync == null) {
		throw new IllegalArgumentException(
				"@EnableAsync is not present on importing class " + importMetadata.getClassName());
	}
}
 
Example 22
public void setImportMetadata(AnnotationMetadata importMetadata) {
    Map<String, Object> enableAttrMap = importMetadata.getAnnotationAttributes(EnableRedisHttpSession.class.getName());
    AnnotationAttributes enableAttrs = AnnotationAttributes.fromMap(enableAttrMap);
    this.maxInactiveIntervalInSeconds = enableAttrs.getNumber("maxInactiveIntervalInSeconds");
    String redisNamespaceValue = enableAttrs.getString("redisNamespace");
    if (StringUtils.hasText(redisNamespaceValue)) {
        this.redisNamespace = this.embeddedValueResolver.resolveStringValue(redisNamespaceValue);
    }

    this.redisFlushMode = enableAttrs.getEnum("redisFlushMode");
}
 
Example 23
Source Project: onetwo   Source File: AbstractImportRegistrar.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
	Class<? extends Annotation> componentAnnoClass = getComponentAnnotationClass();
	List<BeanDefinition> beandefList = scanBeanDefinitions(importingClassMetadata);
	beandefList.stream().filter(AnnotatedBeanDefinition.class::isInstance)
					.forEach(bd->{
						AnnotatedBeanDefinition beanDefinition = (AnnotatedBeanDefinition) bd;
						AnnotationMetadata annotationMetadata = beanDefinition.getMetadata();
						Assert.isTrue(annotationMetadata.isInterface(),
								"@"+componentAnnoClass.getSimpleName()+" can only be specified on an interface");

						AnnotationAttributes tagAttributes = SpringUtils.getAnnotationAttributes(annotationMetadata, componentAnnoClass);
						registerComponent(registry, annotationMetadata, tagAttributes);
					});
}
 
Example 24
Source Project: spring4-understanding   Source File: MergedSqlConfig.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Construct a {@code MergedSqlConfig} instance by merging the configuration
 * from the supplied local (potentially method-level) {@code @SqlConfig} annotation
 * with class-level configuration discovered on the supplied {@code testClass}.
 * <p>Local configuration overrides class-level configuration.
 * <p>If the test class is not annotated with {@code @SqlConfig}, no merging
 * takes place and the local configuration is used "as is".
 */
MergedSqlConfig(SqlConfig localSqlConfig, Class<?> testClass) {
	Assert.notNull(localSqlConfig, "Local @SqlConfig must not be null");
	Assert.notNull(testClass, "testClass must not be null");

	// Get global attributes, if any.
	AnnotationAttributes attributes = AnnotatedElementUtils.findMergedAnnotationAttributes(testClass,
		SqlConfig.class.getName(), false, false);

	// Override global attributes with local attributes.
	if (attributes != null) {
		for (String key : attributes.keySet()) {
			Object value = AnnotationUtils.getValue(localSqlConfig, key);
			if (value != null) {
				// Is the value explicit (i.e., not a 'default')?
				if (!value.equals("") && (value != TransactionMode.DEFAULT) && (value != ErrorMode.DEFAULT)) {
					attributes.put(key, value);
				}
			}
		}
	}
	else {
		// Otherwise, use local attributes only.
		attributes = AnnotationUtils.getAnnotationAttributes(localSqlConfig, false, false);
	}

	this.dataSource = attributes.getString("dataSource");
	this.transactionManager = attributes.getString("transactionManager");
	this.transactionMode = getEnum(attributes, "transactionMode", TransactionMode.DEFAULT, TransactionMode.INFERRED);
	this.encoding = attributes.getString("encoding");
	this.separator = getString(attributes, "separator", ScriptUtils.DEFAULT_STATEMENT_SEPARATOR);
	this.commentPrefix = getString(attributes, "commentPrefix", ScriptUtils.DEFAULT_COMMENT_PREFIX);
	this.blockCommentStartDelimiter = getString(attributes, "blockCommentStartDelimiter",
		ScriptUtils.DEFAULT_BLOCK_COMMENT_START_DELIMITER);
	this.blockCommentEndDelimiter = getString(attributes, "blockCommentEndDelimiter",
		ScriptUtils.DEFAULT_BLOCK_COMMENT_END_DELIMITER);
	this.errorMode = getEnum(attributes, "errorMode", ErrorMode.DEFAULT, ErrorMode.FAIL_ON_ERROR);
}
 
Example 25
@Override
public String[] selectImports(@NonNull AnnotationMetadata metadata) {
    AnnotationAttributes attributes = AnnotationAttributes.fromMap(metadata.getAnnotationAttributes(EnableSchedulerLock.class.getName(), false));
    InterceptMode mode = attributes.getEnum("interceptMode");
    if (mode == PROXY_METHOD) {
        return new String[]{AutoProxyRegistrar.class.getName(), MethodProxyLockConfiguration.class.getName()};
    } else if (mode == PROXY_SCHEDULER) {
        return new String[]{AutoProxyRegistrar.class.getName(), SchedulerProxyLockConfiguration.class.getName(), RegisterDefaultTaskSchedulerPostProcessor.class.getName()};
    } else {
        throw new UnsupportedOperationException("Unknown mode " + mode);
    }

}
 
Example 26
Source Project: lams   Source File: AnnotationConfigUtils.java    License: GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
static Set<AnnotationAttributes> attributesForRepeatable(AnnotationMetadata metadata,
		String containerClassName, String annotationClassName) {

	Set<AnnotationAttributes> result = new LinkedHashSet<AnnotationAttributes>();
	addAttributesIfNotNull(result, metadata.getAnnotationAttributes(annotationClassName, false));

	Map<String, Object> container = metadata.getAnnotationAttributes(containerClassName, false);
	if (container != null && container.containsKey("value")) {
		for (Map<String, Object> containedAttributes : (Map<String, Object>[]) container.get("value")) {
			addAttributesIfNotNull(result, containedAttributes);
		}
	}
	return Collections.unmodifiableSet(result);
}
 
Example 27
@Override
public TransactionAttribute parseTransactionAnnotation(AnnotatedElement ae) {
	AnnotationAttributes attributes = AnnotatedElementUtils.getMergedAnnotationAttributes(ae, Transactional.class);
	if (attributes != null) {
		return parseTransactionAnnotation(attributes);
	}
	else {
		return null;
	}
}
 
Example 28
Source Project: spring-analysis-note   Source File: BeanAnnotationHelper.java    License: MIT License 5 votes vote down vote up
public static boolean isScopedProxy(Method beanMethod) {
	Boolean scopedProxy = scopedProxyCache.get(beanMethod);
	if (scopedProxy == null) {
		AnnotationAttributes scope =
				AnnotatedElementUtils.findMergedAnnotationAttributes(beanMethod, Scope.class, false, false);
		scopedProxy = (scope != null && scope.getEnum("proxyMode") != ScopedProxyMode.NO);
		scopedProxyCache.put(beanMethod, scopedProxy);
	}
	return scopedProxy;
}
 
Example 29
Source Project: spring-analysis-note   Source File: AutoProxyRegistrar.java    License: MIT License 5 votes vote down vote up
/**
 * Register, escalate, and configure the standard auto proxy creator (APC) against the
 * given registry. Works by finding the nearest annotation declared on the importing
 * {@code @Configuration} class that has both {@code mode} and {@code proxyTargetClass}
 * attributes. If {@code mode} is set to {@code PROXY}, the APC is registered; if
 * {@code proxyTargetClass} is set to {@code true}, then the APC is forced to use
 * subclass (CGLIB) proxying.
 * <p>Several {@code @Enable*} annotations expose both {@code mode} and
 * {@code proxyTargetClass} attributes. It is important to note that most of these
 * capabilities end up sharing a {@linkplain AopConfigUtils#AUTO_PROXY_CREATOR_BEAN_NAME
 * single APC}. For this reason, this implementation doesn't "care" exactly which
 * annotation it finds -- as long as it exposes the right {@code mode} and
 * {@code proxyTargetClass} attributes, the APC can be registered and configured all
 * the same.
 */
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
	boolean candidateFound = false;
	Set<String> annTypes = importingClassMetadata.getAnnotationTypes();
	for (String annType : annTypes) {
		AnnotationAttributes candidate = AnnotationConfigUtils.attributesFor(importingClassMetadata, annType);
		if (candidate == null) {
			continue;
		}
		Object mode = candidate.get("mode");
		Object proxyTargetClass = candidate.get("proxyTargetClass");
		if (mode != null && proxyTargetClass != null && AdviceMode.class == mode.getClass() &&
				Boolean.class == proxyTargetClass.getClass()) {
			candidateFound = true;
			if (mode == AdviceMode.PROXY) {
				AopConfigUtils.registerAutoProxyCreatorIfNecessary(registry);
				if ((Boolean) proxyTargetClass) {
					AopConfigUtils.forceAutoProxyCreatorToUseClassProxying(registry);
					return;
				}
			}
		}
	}
	if (!candidateFound && logger.isInfoEnabled()) {
		String name = getClass().getSimpleName();
		logger.info(String.format("%s was imported but no annotations were found " +
				"having both 'mode' and 'proxyTargetClass' attributes of type " +
				"AdviceMode and boolean respectively. This means that auto proxy " +
				"creator registration and configuration may not have occurred as " +
				"intended, and components may not be proxied as expected. Check to " +
				"ensure that %s has been @Import'ed on the same class where these " +
				"annotations are declared; otherwise remove the import of %s " +
				"altogether.", name, name, name));
	}
}
 
Example 30
@Override
public void setImportMetadata(AnnotationMetadata importMetadata) {
	this.enableAsync = AnnotationAttributes.fromMap(
			importMetadata.getAnnotationAttributes(EnableAsync.class.getName(), false));
	if (this.enableAsync == null) {
		throw new IllegalArgumentException(
				"@EnableAsync is not present on importing class " + importMetadata.getClassName());
	}
}