Java Code Examples for org.springframework.core.annotation.AnnotationAttributes#getBoolean()

The following examples show how to use org.springframework.core.annotation.AnnotationAttributes#getBoolean() . 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
Source File: AspectJAutoProxyRegistrar.java    From spring-analysis-note with 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 2
Source File: ContextRegionConfigurationRegistrar.java    From spring-cloud-aws with Apache License 2.0 6 votes vote down vote up
@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 3
Source File: DurableClientConfiguration.java    From spring-boot-data-geode with Apache License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings("all")
public void setImportMetadata(AnnotationMetadata importMetadata) {

	if (isAnnotationPresent(importMetadata)) {

		AnnotationAttributes enableDurableClientAttributes = getAnnotationAttributes(importMetadata);

		this.durableClientId = enableDurableClientAttributes.containsKey("id")
			? enableDurableClientAttributes.getString("id")
			: null;

		this.durableClientTimeout = enableDurableClientAttributes.containsKey("timeout")
			? enableDurableClientAttributes.getNumber("timeout")
			: DEFAULT_DURABLE_CLIENT_TIMEOUT;

		this.keepAlive = enableDurableClientAttributes.containsKey("keepAlive")
			? enableDurableClientAttributes.getBoolean("keepAlive")
			: DEFAULT_KEEP_ALIVE;

		this.readyForEvents = enableDurableClientAttributes.containsKey("readyForEvents")
			? enableDurableClientAttributes.getBoolean("readyForEvents")
			: DEFAULT_READY_FOR_EVENTS;
	}
}
 
Example 4
Source File: DubboConfigConfigurationSelector.java    From dubbo-2.6.5 with Apache License 2.0 5 votes vote down vote up
@Override
    public String[] selectImports(AnnotationMetadata importingClassMetadata) {

//        查询@EnableDubboConfig注解的属性值
        AnnotationAttributes attributes = AnnotationAttributes.fromMap(
                importingClassMetadata.getAnnotationAttributes(EnableDubboConfig.class.getName()));

        boolean multiple = attributes.getBoolean("multiple");

        if (multiple) { //属性是否是多个配置
            return of(DubboConfigConfiguration.Multiple.class.getName());
        } else {
            return of(DubboConfigConfiguration.Single.class.getName());
        }
    }
 
Example 5
Source File: ConfigurationClassParser.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Process the given <code>@PropertySource</code> annotation metadata.
 * @param propertySource metadata for the <code>@PropertySource</code> annotation found
 * @throws IOException if loading a property source failed
 */
private void processPropertySource(AnnotationAttributes propertySource) throws IOException {
	String name = propertySource.getString("name");
	if (!StringUtils.hasLength(name)) {
		name = null;
	}
	String encoding = propertySource.getString("encoding");
	if (!StringUtils.hasLength(encoding)) {
		encoding = null;
	}
	String[] locations = propertySource.getStringArray("value");
	Assert.isTrue(locations.length > 0, "At least one @PropertySource(value) location is required");
	boolean ignoreResourceNotFound = propertySource.getBoolean("ignoreResourceNotFound");

	Class<? extends PropertySourceFactory> factoryClass = propertySource.getClass("factory");
	PropertySourceFactory factory = (factoryClass == PropertySourceFactory.class ?
			DEFAULT_PROPERTY_SOURCE_FACTORY : BeanUtils.instantiateClass(factoryClass));

	for (String location : locations) {
		try {
			String resolvedLocation = this.environment.resolveRequiredPlaceholders(location);
			Resource resource = this.resourceLoader.getResource(resolvedLocation);
			addPropertySource(factory.createPropertySource(name, new EncodedResource(resource, encoding)));
		}
		catch (IllegalArgumentException | FileNotFoundException | UnknownHostException ex) {
			// Placeholders not resolvable or resource not found when trying to open it
			if (ignoreResourceNotFound) {
				if (logger.isInfoEnabled()) {
					logger.info("Properties location [" + location + "] not resolvable: " + ex.getMessage());
				}
			}
			else {
				throw ex;
			}
		}
	}
}
 
Example 6
Source File: ConfigurationClassParser.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Process the given <code>@PropertySource</code> annotation metadata.
 * @param propertySource metadata for the <code>@PropertySource</code> annotation found
 * @throws IOException if loading a property source failed
 */
private void processPropertySource(AnnotationAttributes propertySource) throws IOException {
	String name = propertySource.getString("name");
	if (!StringUtils.hasLength(name)) {
		name = null;
	}
	String encoding = propertySource.getString("encoding");
	if (!StringUtils.hasLength(encoding)) {
		encoding = null;
	}
	String[] locations = propertySource.getStringArray("value");
	Assert.isTrue(locations.length > 0, "At least one @PropertySource(value) location is required");
	boolean ignoreResourceNotFound = propertySource.getBoolean("ignoreResourceNotFound");

	Class<? extends PropertySourceFactory> factoryClass = propertySource.getClass("factory");
	PropertySourceFactory factory = (factoryClass == PropertySourceFactory.class ?
			DEFAULT_PROPERTY_SOURCE_FACTORY : BeanUtils.instantiateClass(factoryClass));

	for (String location : locations) {
		try {
			String resolvedLocation = this.environment.resolveRequiredPlaceholders(location);
			Resource resource = this.resourceLoader.getResource(resolvedLocation);
			addPropertySource(factory.createPropertySource(name, new EncodedResource(resource, encoding)));
		}
		catch (IllegalArgumentException | FileNotFoundException | UnknownHostException ex) {
			// Placeholders not resolvable or resource not found when trying to open it
			if (ignoreResourceNotFound) {
				if (logger.isInfoEnabled()) {
					logger.info("Properties location [" + location + "] not resolvable: " + ex.getMessage());
				}
			}
			else {
				throw ex;
			}
		}
	}
}
 
Example 7
Source File: EnableDiscoveryClientImportSelector.java    From spring-cloud-commons with Apache License 2.0 5 votes vote down vote up
@Override
public String[] selectImports(AnnotationMetadata metadata) {
	String[] imports = super.selectImports(metadata);

	AnnotationAttributes attributes = AnnotationAttributes.fromMap(
			metadata.getAnnotationAttributes(getAnnotationClass().getName(), true));

	boolean autoRegister = attributes.getBoolean("autoRegister");

	if (autoRegister) {
		List<String> importsList = new ArrayList<>(Arrays.asList(imports));
		importsList.add(
				"org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationConfiguration");
		imports = importsList.toArray(new String[0]);
	}
	else {
		Environment env = getEnvironment();
		if (ConfigurableEnvironment.class.isInstance(env)) {
			ConfigurableEnvironment configEnv = (ConfigurableEnvironment) env;
			LinkedHashMap<String, Object> map = new LinkedHashMap<>();
			map.put("spring.cloud.service-registry.auto-registration.enabled", false);
			MapPropertySource propertySource = new MapPropertySource(
					"springCloudDiscoveryClient", map);
			configEnv.getPropertySources().addLast(propertySource);
		}

	}

	return imports;
}
 
Example 8
Source File: AbstractTemplateProvider.java    From spring-data-generator with MIT License 5 votes vote down vote up
public AbstractTemplateProvider(AnnotationAttributes attributes) {
    Assert.notNull(attributes, "AnnotationAttributes must not be null!");
    this.excludeClasses = attributes.getClassArray(getExcludeClasses());
    this.postfix = attributes.getString(getPostfix());
    this.debug = attributes.getBoolean("debug");
    this.overwrite = attributes.getBoolean("overwrite");
    if (excludeClasses.length > 0 && debug) {
        SDLogger.debug(String.format("Exclude %s %s in the %s generator", excludeClasses.length, excludeClasses.length == 1 ? "entity":"entities", postfix));
    }
}
 
Example 9
Source File: MvcInterceptorManager.java    From onetwo with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
protected MvcInterceptorMeta asMvcInterceptorMeta(AnnotationAttributes attr){
	List<PropertyAnnoMeta> properties = propertyAnnotationReader.readProperties(attr);
	return new MvcInterceptorMeta((Class<? extends MvcInterceptor>)attr.getClass("value"), 
									attr.getBoolean("alwaysCreate"), 
									properties);
}
 
Example 10
Source File: ProducerRegistar.java    From onetwo with Apache License 2.0 4 votes vote down vote up
@Override
	public void doRegisterBeanDefinitions(AnnotationAttributes attributes, BeanDefinitionRegistry registry) {
		AnnotationAttributes[] producers = attributes.getAnnotationArray("producers");
		if(LangUtils.isEmpty(producers)){
			return ;
		}
		for(AnnotationAttributes producer : producers){
			String producerId = resolveAttribute(producer, "producerId", null);
//			String beanName = "ONS-"+producerId;
			String beanName = producerId;//StringUtils.appendStartWith(producerId, "ons-");
			
			if(registry.containsBeanDefinition(beanName)){
				logger.info("produer[{}] has been registered, ignored...", beanName);
				continue;
			}
			
			boolean transactional = producer.getBoolean("transactional");
			Class<?> producerClass = transactional?ONSTransactionProducerServiceImpl.class:ONSProducerServiceImpl.class;
			
			BeanDefinitionBuilder definition = BeanDefinitionBuilder.genericBeanDefinition(producerClass);
			definition.addPropertyValue("producerId", producerId);
//			definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);
			BeanDefinitionHolder holder = new BeanDefinitionHolder(definition.getBeanDefinition(), beanName);
			holder.getBeanDefinition().setPrimary(producer.getBoolean("primary"));
			
			BeanDefinitionReaderUtils.registerBeanDefinition(holder, registry);
			if(logger.isInfoEnabled()){
				logger.info("register producer {}: {}", producerClass.getSimpleName(), beanName);
			}
			
			if(transactional){
				BeanDefinitionBuilder noTransactionalBean = BeanDefinitionBuilder.genericBeanDefinition(FakeProducerService.class);
//				definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);
				String fakeProducerService = beanName + "-fake";
				BeanDefinitionHolder notTransactionalHolder = new BeanDefinitionHolder(noTransactionalBean.getBeanDefinition(), fakeProducerService);
				BeanDefinitionReaderUtils.registerBeanDefinition(notTransactionalHolder, registry);
				if(logger.isInfoEnabled()){
					logger.info("register producer {}: {}", FakeProducerService.class.getSimpleName(), fakeProducerService);
				}
			}
		}
	}
 
Example 11
Source File: WxMvcConfiguration.java    From FastBootWeixin with Apache License 2.0 4 votes vote down vote up
@Override
public void setImportMetadata(AnnotationMetadata importMetadata) {
    AnnotationAttributes annotationAttributes = AnnotationAttributes.fromMap(
            importMetadata.getAnnotationAttributes(EnableWxMvc.class.getName(), false));
    this.menuAutoCreate = annotationAttributes.getBoolean("menuAutoCreate");
}
 
Example 12
Source File: VaultPropertySourceRegistrar.java    From spring-vault with Apache License 2.0 4 votes vote down vote up
@Override
public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry registry) {

	Assert.notNull(annotationMetadata, "AnnotationMetadata must not be null");
	Assert.notNull(registry, "BeanDefinitionRegistry must not be null");

	if (!registry.isBeanNameInUse("VaultPropertySourceRegistrar")) {
		registry.registerBeanDefinition("VaultPropertySourceRegistrar", BeanDefinitionBuilder //
				.rootBeanDefinition(VaultPropertySourceRegistrar.class) //
				.setRole(BeanDefinition.ROLE_INFRASTRUCTURE) //
				.getBeanDefinition());
	}

	Set<AnnotationAttributes> propertySources = attributesForRepeatable(annotationMetadata,
			VaultPropertySources.class.getName(), VaultPropertySource.class.getName());

	int counter = 0;

	for (AnnotationAttributes propertySource : propertySources) {

		String[] paths = propertySource.getStringArray("value");
		String ref = propertySource.getString("vaultTemplateRef");
		String propertyNamePrefix = propertySource.getString("propertyNamePrefix");
		Renewal renewal = propertySource.getEnum("renewal");
		boolean ignoreSecretNotFound = propertySource.getBoolean("ignoreSecretNotFound");

		Assert.isTrue(paths.length > 0, "At least one @VaultPropertySource(value) location is required");

		Assert.hasText(ref, "'vaultTemplateRef' in @EnableVaultPropertySource must not be empty");

		PropertyTransformer propertyTransformer = StringUtils.hasText(propertyNamePrefix)
				? PropertyTransformers.propertyNamePrefix(propertyNamePrefix) : PropertyTransformers.noop();

		for (String propertyPath : paths) {

			if (!StringUtils.hasText(propertyPath)) {
				continue;
			}

			AbstractBeanDefinition beanDefinition = createBeanDefinition(ref, renewal, propertyTransformer,
					ignoreSecretNotFound, potentiallyResolveRequiredPlaceholders(propertyPath));

			do {
				String beanName = "vaultPropertySource#" + counter;

				if (!registry.isBeanNameInUse(beanName)) {
					registry.registerBeanDefinition(beanName, beanDefinition);
					break;
				}

				counter++;
			}
			while (true);
		}
	}
}
 
Example 13
Source File: DubboConfigBindingRegistrar.java    From dubbo-2.6.5 with Apache License 2.0 3 votes vote down vote up
protected void registerBeanDefinitions(AnnotationAttributes attributes, BeanDefinitionRegistry registry) {

//        解析prefix属性,可以用占位符
        String prefix = environment.resolvePlaceholders(attributes.getString("prefix"));

//        type属性值,AbstractConfig的实现类
        Class<? extends AbstractConfig> configClass = attributes.getClass("type");

        boolean multiple = attributes.getBoolean("multiple");

//        注册dubbo配置属性=》
        registerDubboConfigBeans(prefix, configClass, multiple, registry);

    }
 
Example 14
Source File: ContextConfigurationAttributes.java    From spring-analysis-note with MIT License 3 votes vote down vote up
/**
 * Construct a new {@link ContextConfigurationAttributes} instance for the
 * supplied {@link AnnotationAttributes} (parsed from a
 * {@link ContextConfiguration @ContextConfiguration} annotation) and
 * the {@linkplain Class test class} that declared them.
 * @param declaringClass the test class that declared {@code @ContextConfiguration}
 * @param annAttrs the annotation attributes from which to retrieve the attributes
 */
@SuppressWarnings("unchecked")
public ContextConfigurationAttributes(Class<?> declaringClass, AnnotationAttributes annAttrs) {
	this(declaringClass, annAttrs.getStringArray("locations"), annAttrs.getClassArray("classes"),
			annAttrs.getBoolean("inheritLocations"),
			(Class<? extends ApplicationContextInitializer<?>>[]) annAttrs.getClassArray("initializers"),
			annAttrs.getBoolean("inheritInitializers"), annAttrs.getString("name"), annAttrs.getClass("loader"));
}
 
Example 15
Source File: ContextConfigurationAttributes.java    From spring4-understanding with Apache License 2.0 3 votes vote down vote up
/**
 * Construct a new {@link ContextConfigurationAttributes} instance for the
 * supplied {@link AnnotationAttributes} (parsed from a
 * {@link ContextConfiguration @ContextConfiguration} annotation) and
 * the {@linkplain Class test class} that declared them.
 * @param declaringClass the test class that declared {@code @ContextConfiguration}
 * @param annAttrs the annotation attributes from which to retrieve the attributes
 */
@SuppressWarnings("unchecked")
public ContextConfigurationAttributes(Class<?> declaringClass, AnnotationAttributes annAttrs) {
	this(declaringClass, annAttrs.getStringArray("locations"), annAttrs.getClassArray("classes"), annAttrs.getBoolean("inheritLocations"),
		(Class<? extends ApplicationContextInitializer<? extends ConfigurableApplicationContext>>[]) annAttrs.getClassArray("initializers"),
		annAttrs.getBoolean("inheritInitializers"), annAttrs.getString("name"), (Class<? extends ContextLoader>) annAttrs.getClass("loader"));
}
 
Example 16
Source File: AutowiredAnnotationBeanPostProcessor.java    From blog_demos with Apache License 2.0 2 votes vote down vote up
/**
 * Determine if the annotated field or method requires its dependency.
 * <p>A 'required' dependency means that autowiring should fail when no beans
 * are found. Otherwise, the autowiring process will simply bypass the field
 * or method when no beans are found.
 * @param annotation the Autowired annotation
 * @return whether the annotation indicates that a dependency is required
 */
protected boolean determineRequiredStatus(AnnotationAttributes annotation) {
	return (!annotation.containsKey(this.requiredParameterName) ||
			this.requiredParameterValue == annotation.getBoolean(this.requiredParameterName));
}
 
Example 17
Source File: AutowiredAnnotationBeanPostProcessor.java    From lams with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Determine if the annotated field or method requires its dependency.
 * <p>A 'required' dependency means that autowiring should fail when no beans
 * are found. Otherwise, the autowiring process will simply bypass the field
 * or method when no beans are found.
 * @param ann the Autowired annotation
 * @return whether the annotation indicates that a dependency is required
 */
protected boolean determineRequiredStatus(AnnotationAttributes ann) {
	return (!ann.containsKey(this.requiredParameterName) ||
			this.requiredParameterValue == ann.getBoolean(this.requiredParameterName));
}
 
Example 18
Source File: AutowiredAnnotationBeanPostProcessor.java    From java-technology-stack with MIT License 2 votes vote down vote up
/**
 * Determine if the annotated field or method requires its dependency.
 * <p>A 'required' dependency means that autowiring should fail when no beans
 * are found. Otherwise, the autowiring process will simply bypass the field
 * or method when no beans are found.
 * @param ann the Autowired annotation
 * @return whether the annotation indicates that a dependency is required
 */
protected boolean determineRequiredStatus(AnnotationAttributes ann) {
	return (!ann.containsKey(this.requiredParameterName) ||
			this.requiredParameterValue == ann.getBoolean(this.requiredParameterName));
}
 
Example 19
Source File: AutowiredAnnotationBeanPostProcessor.java    From spring4-understanding with Apache License 2.0 2 votes vote down vote up
/**
 * Determine if the annotated field or method requires its dependency.
 * <p>A 'required' dependency means that autowiring should fail when no beans
 * are found. Otherwise, the autowiring process will simply bypass the field
 * or method when no beans are found.
 * @param ann the Autowired annotation
 * @return whether the annotation indicates that a dependency is required
 */
protected boolean determineRequiredStatus(AnnotationAttributes ann) {
	return (!ann.containsKey(this.requiredParameterName) ||
			this.requiredParameterValue == ann.getBoolean(this.requiredParameterName));
}
 
Example 20
Source File: AutowiredAnnotationBeanPostProcessor.java    From spring-analysis-note with MIT License 2 votes vote down vote up
/**
 * Determine if the annotated field or method requires its dependency.
 * <p>A 'required' dependency means that autowiring should fail when no beans
 * are found. Otherwise, the autowiring process will simply bypass the field
 * or method when no beans are found.
 * @param ann the Autowired annotation
 * @return whether the annotation indicates that a dependency is required
 * @deprecated since 5.2, in favor of {@link #determineRequiredStatus(MergedAnnotation)}
 */
@Deprecated
protected boolean determineRequiredStatus(AnnotationAttributes ann) {
	return (!ann.containsKey(this.requiredParameterName) ||
			this.requiredParameterValue == ann.getBoolean(this.requiredParameterName));
}