org.springframework.core.io.support.SpringFactoriesLoader Java Examples

The following examples show how to use org.springframework.core.io.support.SpringFactoriesLoader. 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: BootstrapImportSelector.java    From spring-cloud-commons with Apache License 2.0 6 votes vote down vote up
@Override
public String[] selectImports(AnnotationMetadata annotationMetadata) {
	ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
	// Use names and ensure unique to protect against duplicates
	List<String> names = new ArrayList<>(SpringFactoriesLoader
			.loadFactoryNames(BootstrapConfiguration.class, classLoader));
	names.addAll(Arrays.asList(StringUtils.commaDelimitedListToStringArray(
			this.environment.getProperty("spring.cloud.bootstrap.sources", ""))));

	List<OrderedAnnotatedElement> elements = new ArrayList<>();
	for (String name : names) {
		try {
			elements.add(
					new OrderedAnnotatedElement(this.metadataReaderFactory, name));
		}
		catch (IOException e) {
			continue;
		}
	}
	AnnotationAwareOrderComparator.sort(elements);

	String[] classNames = elements.stream().map(e -> e.name).toArray(String[]::new);

	return classNames;
}
 
Example #2
Source File: TemplateVariableProviderFactory.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
List<TemplateVariableProvider> getTemplateVariableProviders() {
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    Set<String> factories = new LinkedHashSet<>(SpringFactoriesLoader.loadFactoryNames(
            TemplateVariableProvider.class, Thread.currentThread().getContextClassLoader()));

    return factories.stream()
            .map(new Function<String, TemplateVariableProvider>() {
                @Override
                public TemplateVariableProvider apply(String name) {
                    try {
                        Class<TemplateVariableProvider> instanceClass =
                                (Class<TemplateVariableProvider>) ClassUtils.forName(name, classLoader);
                        return applicationContext.getBean(instanceClass);
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                        return null;
                    }
                }
            }).collect(Collectors.toList());
}
 
Example #3
Source File: TemplateVariableProviderFactory.java    From gravitee-gateway with Apache License 2.0 6 votes vote down vote up
List<TemplateVariableProvider> getTemplateVariableProviders() {
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    Set<String> factories = new LinkedHashSet<>(SpringFactoriesLoader.loadFactoryNames(
            TemplateVariableProvider.class, Thread.currentThread().getContextClassLoader()));

    return factories.stream()
            .map(new Function<String, TemplateVariableProvider>() {
                @Override
                public TemplateVariableProvider apply(String name) {
                    try {
                        Class<TemplateVariableProvider> instanceClass =
                                (Class<TemplateVariableProvider>) ClassUtils.forName(name, classLoader);
                        return applicationContext.getBean(instanceClass);
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                        return null;
                    }
                }
            }).collect(Collectors.toList());
}
 
Example #4
Source File: FunctionType.java    From spring-cloud-function with Apache License 2.0 6 votes vote down vote up
public static boolean isWrapper(Type type) {
	if (type instanceof ParameterizedType) {
		type = ((ParameterizedType) type).getRawType();
	}
	if (transformers == null) {
		transformers = new ArrayList<>();
		transformers.addAll(
				SpringFactoriesLoader.loadFactories(WrapperDetector.class, null));
	}
	for (WrapperDetector transformer : transformers) {
		if (transformer.isWrapper(type)) {
			return true;
		}
	}
	return false;
}
 
Example #5
Source File: DefaultAutoConfigurationImportListener.java    From thinking-in-spring-boot-samples with Apache License 2.0 6 votes vote down vote up
@Override
public void onAutoConfigurationImportEvent(AutoConfigurationImportEvent event) {
    // 获取当前 ClassLoader
    ClassLoader classLoader = event.getClass().getClassLoader();
    // 候选的自动装配类名单
    List<String> candidates =
            SpringFactoriesLoader.loadFactoryNames(EnableAutoConfiguration.class, classLoader);
    // 实际的自动装配类名单
    List<String> configurations = event.getCandidateConfigurations();
    // 排除的自动装配类名单
    Set<String> exclusions = event.getExclusions();
    // 输出各自数量
    System.out.printf("自动装配类名单 - 候选数量:%d,实际数量:%d,排除数量:%s\n",
            candidates.size(), configurations.size(), exclusions.size());
    // 输出实际和排除的自动装配类名单
    System.out.println("实际的自动装配类名单:");
    event.getCandidateConfigurations().forEach(System.out::println);
    System.out.println("排除的自动装配类名单:");
    event.getExclusions().forEach(System.out::println);
}
 
Example #6
Source File: Target_SpringApplication.java    From spring-graalvm-native with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Substitute
private <T> Collection<T> getSpringFactoriesInstances(Class<T> type, Class<?>[] parameterTypes, Object... args) {
	List<T> instances;
	if (type.equals(SpringApplicationRunListener.class)) {
		instances = (List<T>) Arrays.asList(new EventPublishingRunListener((SpringApplication)(Object)this, new String[0])); // TODO convert args
		// Error when using it, and we probably should do that at build time
		//AnnotationAwareOrderComparator.sort(instances);
	}
	else if (type.equals(SpringBootExceptionReporter.class)) {
		instances = (List<T>) Arrays.asList(DiagnosticsProvider.getFailureAnalyzers((ConfigurableApplicationContext) args[0])); // Package private
		// Error when using it, and we probably should do that at build time
		//AnnotationAwareOrderComparator.sort(instances);
	}
	else {
		instances = SpringFactoriesLoader.loadFactories(type, null);
	}
	return instances;
}
 
Example #7
Source File: MultiModuleConfigServicePropertySourceLocator.java    From spring-cloud-formula with Apache License 2.0 6 votes vote down vote up
public static List<ModuleConfiguration> loadApplicationNames(ClassLoader classLoader) {
    try {
        Enumeration<URL> urls = (classLoader != null ?
                classLoader.getResources(SpringFactoriesLoader.FACTORIES_RESOURCE_LOCATION) :
                ClassLoader.getSystemResources(SpringFactoriesLoader.FACTORIES_RESOURCE_LOCATION));
        return Collections.list(urls).stream()
                .map(MultiModuleConfigServicePropertySourceLocator::loadProperties)
                .filter(properties ->  properties.getProperty(APPLICATION_NAME_KEY) != null)
                .flatMap(props -> {
                    String applicationName = props.getProperty(APPLICATION_NAME_KEY);
                    String order = props.getProperty(APPLICATION_NAME_ORDER);
                    return Stream.of(StringUtils.commaDelimitedListToStringArray(applicationName))
                            .map(name ->
                                    new ModuleConfiguration(name, order == null ? 0 : Integer.parseInt(order)));
                })
                .collect(Collectors.toList());
    } catch (IOException ex) {
        throw new IllegalArgumentException("Unable to load multi module configuration " +
                "from location [" + SpringFactoriesLoader.FACTORIES_RESOURCE_LOCATION + "]", ex);
    }
}
 
Example #8
Source File: StubRepository.java    From spring-cloud-contract with Apache License 2.0 6 votes vote down vote up
StubRepository(File repository, List<HttpServerStub> httpServerStubs,
		StubRunnerOptions options) {
	if (!repository.isDirectory()) {
		throw new IllegalArgumentException(
				"Missing descriptor repository under path [" + repository + "]");
	}
	this.contractConverters = SpringFactoriesLoader
			.loadFactories(ContractConverter.class, null);
	if (log.isTraceEnabled()) {
		log.trace(
				"Found the following contract converters " + this.contractConverters);
	}
	this.httpServerStubs = httpServerStubs;
	this.path = repository;
	this.options = options;
	this.stubs = stubs();
	this.contracts = contracts();
	if (log.isTraceEnabled()) {
		log.trace("Found the following contracts " + this.contracts);
	}
}
 
Example #9
Source File: AccessLimitFilter.java    From jim-framework with Apache License 2.0 5 votes vote down vote up
@Override
public Object invoke(RpcInvoker invoker, RpcInvocation invocation) {
    logger.info("before acquire,"+new Date());
    List<AccessLimitService> accessLimitServiceLoader = SpringFactoriesLoader.loadFactories(AccessLimitService.class, null);
    if(!CollectionUtils.isEmpty(accessLimitServiceLoader)){
        AccessLimitService accessLimitService=accessLimitServiceLoader.get(0);
        accessLimitService.acquire(invocation);
    }

    Object rpcResponse=invoker.invoke(invocation);
    logger.info("after acquire,"+new Date());
    return rpcResponse;
}
 
Example #10
Source File: SpringBootSpinProcessEnginePlugin.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
protected void loadSpringBootDataFormats(ClassLoader classloader) {
  List<DataFormatConfigurator> configurators = new ArrayList<>();

  // add the auto-config Jackson Java 8 module configurators
  dataFormatConfiguratorJsr310.ifPresent(configurator -> configurators.add(configurator));
  dataFormatConfiguratorParameterNames.ifPresent(configurator -> configurators.add(configurator));
  dataFormatConfiguratorJdk8.ifPresent(configurator -> configurators.add(configurator));

  // next, add any configurators defined in the spring.factories file
  configurators.addAll(SpringFactoriesLoader.loadFactories(DataFormatConfigurator.class, classloader));

  DataFormats.loadDataFormats(classloader, configurators);
}
 
Example #11
Source File: BootstrapConfigTest.java    From apollo with Apache License 2.0 5 votes vote down vote up
@Test
public void test() {
  List<EnvironmentPostProcessor> processorList =  SpringFactoriesLoader.loadFactories(EnvironmentPostProcessor.class, getClass().getClassLoader());

  Boolean containsApollo = !Collections2.filter(processorList, new Predicate<EnvironmentPostProcessor>() {
        @Override
        public boolean apply(EnvironmentPostProcessor input) {
            return input instanceof ApolloApplicationContextInitializer;
        }
    }).isEmpty();
  Assert.assertTrue(containsApollo);
}
 
Example #12
Source File: StubRunner.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
public StubRunner(StubRunnerOptions stubRunnerOptions, String repositoryPath,
		StubConfiguration stubsConfiguration,
		MessageVerifier<?> contractVerifierMessaging) {
	this.stubsConfiguration = stubsConfiguration;
	this.stubRunnerOptions = stubRunnerOptions;
	List<HttpServerStub> serverStubs = SpringFactoriesLoader
			.loadFactories(HttpServerStub.class, null);
	this.stubRepository = new StubRepository(new File(repositoryPath), serverStubs,
			this.stubRunnerOptions);
	AvailablePortScanner portScanner = new AvailablePortScanner(
			stubRunnerOptions.getMinPortValue(), stubRunnerOptions.getMaxPortValue());
	this.localStubRunner = new StubRunnerExecutor(portScanner,
			contractVerifierMessaging, serverStubs);
}
 
Example #13
Source File: WireMockHttpServerStub.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
private Extension[] responseTransformers() {
	List<WireMockExtensions> wireMockExtensions = SpringFactoriesLoader
			.loadFactories(WireMockExtensions.class, null);
	List<Extension> extensions = new ArrayList<>();
	if (!wireMockExtensions.isEmpty()) {
		for (WireMockExtensions wireMockExtension : wireMockExtensions) {
			extensions.addAll(wireMockExtension.extensions());
		}
	}
	else {
		extensions.add(new DefaultResponseTransformer(false, helpers()));
	}
	return extensions.toArray(new Extension[extensions.size()]);
}
 
Example #14
Source File: AbstractStoreBeanDefinitionRegistrar.java    From spring-content with Apache License 2.0 5 votes vote down vote up
protected boolean multipleStoreImplementationsDetected() {

		boolean multipleModulesFound = SpringFactoriesLoader
				.loadFactoryNames(AbstractStoreFactoryBean.class, resourceLoader.getClassLoader()).size() > 1;

		if (multipleModulesFound) {
			LOGGER.info("Multiple store modules detected.  Entering strict resolution mode");
		}

		return multipleModulesFound;
	}
 
Example #15
Source File: FlowableDefaultPropertiesEnvironmentPostProcessor.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
Loader(ConfigurableEnvironment environment, ResourceLoader resourceLoader) {
    this.environment = environment;
    this.resourceLoader = resourceLoader == null ? new DefaultResourceLoader()
        : resourceLoader;
    this.propertySourceLoaders = SpringFactoriesLoader.loadFactories(
        PropertySourceLoader.class, getClass().getClassLoader());
}
 
Example #16
Source File: SpringBootSpinProcessEnginePlugin.java    From camunda-bpm-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
protected void loadSpringBootDataFormats(ClassLoader classloader) {
  List<DataFormatConfigurator> configurators = new ArrayList<>();

  // add the auto-config Jackson Java 8 module configurators
  dataFormatConfiguratorJsr310.ifPresent(configurator -> configurators.add(configurator));
  dataFormatConfiguratorParameterNames.ifPresent(configurator -> configurators.add(configurator));
  dataFormatConfiguratorJdk8.ifPresent(configurator -> configurators.add(configurator));

  // next, add any configurators defined in the spring.factories file
  configurators.addAll(SpringFactoriesLoader.loadFactories(DataFormatConfigurator.class, classloader));

  DataFormats.loadDataFormats(classloader, configurators);
}
 
Example #17
Source File: MSF4JSpringApplication.java    From msf4j with Apache License 2.0 5 votes vote down vote up
private <T> Collection<? extends T> getSpringFactoriesInstances(Class<T> type,
                                                                Class<?>[] parameterTypes, Object... args) {
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    Set<String> names = new LinkedHashSet<>(
            SpringFactoriesLoader.loadFactoryNames(type, classLoader));
    List<T> instances = createSpringFactoriesInstances(type, parameterTypes,
            classLoader, args, names);
    AnnotationAwareOrderComparator.sort(instances);
    return instances;
}
 
Example #18
Source File: SpringFactoryImportSelector.java    From spring-cloud-commons with Apache License 2.0 5 votes vote down vote up
@Override
public String[] selectImports(AnnotationMetadata metadata) {
	if (!isEnabled()) {
		return new String[0];
	}
	AnnotationAttributes attributes = AnnotationAttributes.fromMap(
			metadata.getAnnotationAttributes(this.annotationClass.getName(), true));

	Assert.notNull(attributes, "No " + getSimpleName() + " attributes found. Is "
			+ metadata.getClassName() + " annotated with @" + getSimpleName() + "?");

	// Find all possible auto configuration classes, filtering duplicates
	List<String> factories = new ArrayList<>(new LinkedHashSet<>(SpringFactoriesLoader
			.loadFactoryNames(this.annotationClass, this.beanClassLoader)));

	if (factories.isEmpty() && !hasDefaultFactory()) {
		throw new IllegalStateException("Annotation @" + getSimpleName()
				+ " found, but there are no implementations. Did you forget to include a starter?");
	}

	if (factories.size() > 1) {
		// there should only ever be one DiscoveryClient, but there might be more than
		// one factory
		this.log.warn("More than one implementation " + "of @" + getSimpleName()
				+ " (now relying on @Conditionals to pick one): " + factories);
	}

	return factories.toArray(new String[factories.size()]);
}
 
Example #19
Source File: CredentialProviderRegistry.java    From syndesis with Apache License 2.0 5 votes vote down vote up
CredentialProviderRegistry(final DataManager dataManager) {
    this.dataManager = dataManager;

    credentialProviderFactories = SpringFactoriesLoader
        .loadFactories(CredentialProviderFactory.class, ClassUtils.getDefaultClassLoader()).stream()
        .collect(Collectors.toMap(CredentialProviderFactory::id, Function.identity()));
}
 
Example #20
Source File: SpringApplication.java    From spring-javaformat with Apache License 2.0 5 votes vote down vote up
private <T> Collection<T> getSpringFactoriesInstances(Class<T> type,
		Class<?>[] parameterTypes, Object... args) {
	ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
	// Use names and ensure unique to protect against duplicates
	Set<String> names = new LinkedHashSet<>(
			SpringFactoriesLoader.loadFactoryNames(type, classLoader));
	List<T> instances = createSpringFactoriesInstances(type, parameterTypes,
			classLoader, args, names);
	AnnotationAwareOrderComparator.sort(instances);
	return instances;
}
 
Example #21
Source File: MultiModuleConfigServicePropertySourceLocator.java    From spring-cloud-formula with Apache License 2.0 5 votes vote down vote up
private static Properties loadProperties(URL url) {
    try {
        return PropertiesLoaderUtils.loadProperties(new UrlResource(url));
    } catch (IOException ex) {
        throw new IllegalArgumentException("Unable to load properties " +
                "from location [" + SpringFactoriesLoader.FACTORIES_RESOURCE_LOCATION + "]", ex);
    }
}
 
Example #22
Source File: DefaultConfigListener.java    From mPaaS with Apache License 2.0 5 votes vote down vote up
@Override
public void starting() {
    if (executed.compareAndSet(false, true)) {
        List<DefaultConfigFactory> defaultConfigs = SpringFactoriesLoader.loadFactories(DefaultConfigFactory.class, this.getClass().getClassLoader());
        Map<String, Object> defaultConfig = new Hashtable<>(1);
        for (DefaultConfigFactory defaultConfigFactory : defaultConfigs) {
            defaultConfig.putAll(defaultConfigFactory.defaultConfig());
        }
        springApplication.setDefaultProperties(defaultConfig);
    }
}
 
Example #23
Source File: DefaultConfigListener.java    From mPass with Apache License 2.0 5 votes vote down vote up
@Override
public void starting() {
    if (executed.compareAndSet(false, true)) {
        List<DefaultConfigFactory> defaultConfigs = SpringFactoriesLoader.loadFactories(DefaultConfigFactory.class, this.getClass().getClassLoader());
        Map<String, Object> defaultConfig = new Hashtable<>(1);
        for (DefaultConfigFactory defaultConfigFactory : defaultConfigs) {
            defaultConfig.putAll(defaultConfigFactory.defaultConfig());
        }
        springApplication.setDefaultProperties(defaultConfig);
    }
}
 
Example #24
Source File: SpringSPITest.java    From spi-imp with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void sayHello() throws Exception {
    List<OrderService> services = SpringFactoriesLoader.loadFactories(OrderService.class, null);
    for (OrderService service : services) {
        service.getOrder("worder.");
    }
}
 
Example #25
Source File: AdminEndpointApplicationRunListener.java    From Moss with Apache License 2.0 5 votes vote down vote up
@Override
public void environmentPrepared(ConfigurableEnvironment env) {
    if("bootstrap".equals(env.getProperty("spring.config.name"))) {
        List<EnvironmentCustomizer> environmentCustomizers =
        SpringFactoriesLoader.loadFactories(EnvironmentCustomizer.class, AdminEndpointApplicationRunListener.class.getClassLoader());
        if(CollectionUtils.isEmpty(environmentCustomizers)) return;
        for(EnvironmentCustomizer customizer: environmentCustomizers) {
            customizer.customize(env);
        }
    }

}
 
Example #26
Source File: AdminEndpointApplicationRunListener.java    From Moss with Apache License 2.0 5 votes vote down vote up
@Override
public void environmentPrepared(ConfigurableEnvironment env) {
    if("bootstrap".equals(env.getProperty("spring.config.name"))) {
        List<EnvironmentCustomizer> environmentCustomizers =
                SpringFactoriesLoader.loadFactories(EnvironmentCustomizer.class, AdminEndpointApplicationRunListener.class.getClassLoader());
        if(CollectionUtils.isEmpty(environmentCustomizers)) return;
        for(EnvironmentCustomizer customizer: environmentCustomizers) {
            customizer.customize(env);
        }
    }
}
 
Example #27
Source File: BladeFeignClientsRegistrar.java    From blade-tool with GNU Lesser General Public License v3.0 4 votes vote down vote up
private void registerFeignClients(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
	List<String> feignClients = SpringFactoriesLoader.loadFactoryNames(getSpringFactoriesLoaderFactoryClass(), getBeanClassLoader());
	// 如果 spring.factories 里为空
	if (feignClients.isEmpty()) {
		return;
	}
	for (String className : feignClients) {
		try {
			Class<?> clazz = beanClassLoader.loadClass(className);
			AnnotationAttributes attributes = AnnotatedElementUtils.getMergedAnnotationAttributes(clazz, FeignClient.class);
			if (attributes == null) {
				continue;
			}
			// 如果已经存在该 bean,支持原生的 Feign
			if (registry.containsBeanDefinition(className)) {
				continue;
			}
			registerClientConfiguration(registry, getClientName(attributes), attributes.get("configuration"));

			validate(attributes);
			BeanDefinitionBuilder definition = BeanDefinitionBuilder.genericBeanDefinition(FeignClientFactoryBean.class);
			definition.addPropertyValue("url", getUrl(attributes));
			definition.addPropertyValue("path", getPath(attributes));
			String name = getName(attributes);
			definition.addPropertyValue("name", name);

			// 兼容最新版本的 spring-cloud-openfeign,尚未发布
			StringBuilder aliasBuilder = new StringBuilder(18);
			if (attributes.containsKey("contextId")) {
				String contextId = getContextId(attributes);
				aliasBuilder.append(contextId);
				definition.addPropertyValue("contextId", contextId);
			} else {
				aliasBuilder.append(name);
			}

			definition.addPropertyValue("type", className);
			definition.addPropertyValue("decode404", attributes.get("decode404"));
			definition.addPropertyValue("fallback", attributes.get("fallback"));
			definition.addPropertyValue("fallbackFactory", attributes.get("fallbackFactory"));
			definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);

			AbstractBeanDefinition beanDefinition = definition.getBeanDefinition();

			// alias
			String alias = aliasBuilder.append("FeignClient").toString();

			// has a default, won't be null
			boolean primary = (Boolean)attributes.get("primary");

			beanDefinition.setPrimary(primary);

			String qualifier = getQualifier(attributes);
			if (StringUtils.hasText(qualifier)) {
				alias = qualifier;
			}

			BeanDefinitionHolder holder = new BeanDefinitionHolder(beanDefinition, className, new String[] { alias });
			BeanDefinitionReaderUtils.registerBeanDefinition(holder, registry);

		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
}
 
Example #28
Source File: Packaging.java    From initializr with Apache License 2.0 4 votes vote down vote up
static Packaging forId(String id) {
	return SpringFactoriesLoader.loadFactories(PackagingFactory.class, Packaging.class.getClassLoader()).stream()
			.map((factory) -> factory.createPackaging(id)).filter(Objects::nonNull).findFirst()
			.orElseThrow(() -> new IllegalStateException("Unrecognized packaging id '" + id + "'"));
}
 
Example #29
Source File: Language.java    From initializr with Apache License 2.0 4 votes vote down vote up
static Language forId(String id, String jvmVersion) {
	return SpringFactoriesLoader.loadFactories(LanguageFactory.class, LanguageFactory.class.getClassLoader())
			.stream().map((factory) -> factory.createLanguage(id, jvmVersion)).filter(Objects::nonNull).findFirst()
			.orElseThrow(() -> new IllegalStateException("Unrecognized language id '" + id + "'"));
}
 
Example #30
Source File: BuildSystem.java    From initializr with Apache License 2.0 4 votes vote down vote up
static BuildSystem forIdAndDialect(String id, String dialect) {
	return SpringFactoriesLoader.loadFactories(BuildSystemFactory.class, BuildSystem.class.getClassLoader())
			.stream().map((factory) -> factory.createBuildSystem(id, dialect)).filter(Objects::nonNull).findFirst()
			.orElseThrow(() -> new IllegalStateException(
					"Unrecognized build system id '" + id + "' and dialect '" + dialect + "'"));
}