类org.springframework.core.env.StandardEnvironment源码实例Demo

下面列出了怎么用org.springframework.core.env.StandardEnvironment的API类实例代码及写法,或者点击链接到github查看源代码。

@Test
public void customPlaceholderPrefixAndSuffix() {
	PropertySourcesPlaceholderConfigurer ppc = new PropertySourcesPlaceholderConfigurer();
	ppc.setPlaceholderPrefix("@<");
	ppc.setPlaceholderSuffix(">");

	DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
	bf.registerBeanDefinition("testBean",
			rootBeanDefinition(TestBean.class)
			.addPropertyValue("name", "@<key1>")
			.addPropertyValue("sex", "${key2}")
			.getBeanDefinition());

	System.setProperty("key1", "systemKey1Value");
	System.setProperty("key2", "systemKey2Value");
	ppc.setEnvironment(new StandardEnvironment());
	ppc.postProcessBeanFactory(bf);
	System.clearProperty("key1");
	System.clearProperty("key2");

	assertThat(bf.getBean(TestBean.class).getName(), is("systemKey1Value"));
	assertThat(bf.getBean(TestBean.class).getSex(), is("${key2}"));
}
 
源代码2 项目: shardingsphere   文件: DataSourceMapSetterTest.java
@SneakyThrows
@Test
public void assetMergedReplaceAndAdd() {
    MockEnvironment mockEnvironment = new MockEnvironment();
    mockEnvironment.setProperty("spring.shardingsphere.datasource.names", "ds0,ds1");
    mockEnvironment.setProperty("spring.shardingsphere.datasource.common.type", "org.apache.commons.dbcp2.BasicDataSource");
    mockEnvironment.setProperty("spring.shardingsphere.datasource.common.driver-class-name", "org.h2.Driver");
    mockEnvironment.setProperty("spring.shardingsphere.datasource.common.max-total", "100");
    mockEnvironment.setProperty("spring.shardingsphere.datasource.common.username", "Asa");
    mockEnvironment.setProperty("spring.shardingsphere.datasource.common.password", "123");
    mockEnvironment.setProperty("spring.shardingsphere.datasource.ds0.url", "jdbc:h2:mem:ds;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MYSQL");
    mockEnvironment.setProperty("spring.shardingsphere.datasource.ds0.username", "sa");
    mockEnvironment.setProperty("spring.shardingsphere.datasource.ds0.max-total", "50");
    mockEnvironment.setProperty("spring.shardingsphere.datasource.ds0.password", "");
    mockEnvironment.setProperty("spring.shardingsphere.datasource.ds1.url", "jdbc:h2:mem:ds;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MYSQL");
    mockEnvironment.setProperty("spring.shardingsphere.datasource.ds1.username", "sa");
    mockEnvironment.setProperty("spring.shardingsphere.datasource.ds1.max-total", "150");
    mockEnvironment.setProperty("spring.shardingsphere.datasource.ds1.password", "");
    StandardEnvironment standardEnvironment = new StandardEnvironment();
    standardEnvironment.merge(mockEnvironment);
    Map<String, DataSource> dataSourceMap = DataSourceMapSetter.getDataSourceMap(standardEnvironment);
    assertThat(dataSourceMap.size(), is(2));
    assertThat(dataSourceMap.get("ds0").getConnection().getMetaData().getUserName(), is("SA"));
    assertThat(dataSourceMap.get("ds1").getConnection().getMetaData().getUserName(), is("SA"));
}
 
源代码3 项目: DataSphereStudio   文件: DSSSpringApplication.java
private static void addOrUpdateRemoteConfig(Environment env, boolean isUpdateOrNot) {
    StandardEnvironment environment = (StandardEnvironment) env;
    PropertySource propertySource = environment.getPropertySources().get("bootstrapProperties");
    if(propertySource == null) {
        return;
    }
    CompositePropertySource source = (CompositePropertySource) propertySource;
    for (String key: source.getPropertyNames()) {
        Object val = source.getProperty(key);
        if(val == null) {
            continue;
        }
        if(isUpdateOrNot) {
            logger.info("update remote config => " + key + " = " + source.getProperty(key));
            BDPConfiguration.set(key, val.toString());
        } else {
            logger.info("add remote config => " + key + " = " + source.getProperty(key));
            BDPConfiguration.setIfNotExists(key, val.toString());
        }
    }
}
 
@Test
public void getBean_withActiveProfile() {
	ConfigurableEnvironment env = new StandardEnvironment();
	env.setActiveProfiles("dev");

	DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
	XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(bf);
	reader.setEnvironment(env);
	reader.loadBeanDefinitions(XML);

	bf.getBean("devOnlyBean"); // should not throw NSBDE

	Object foo = bf.getBean("foo");
	assertThat(foo, instanceOf(Integer.class));

	bf.getBean("devOnlyBean");
}
 
@Test
public void customPlaceholderPrefixAndSuffix() {
	PropertySourcesPlaceholderConfigurer ppc = new PropertySourcesPlaceholderConfigurer();
	ppc.setPlaceholderPrefix("@<");
	ppc.setPlaceholderSuffix(">");

	DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
	bf.registerBeanDefinition("testBean",
			rootBeanDefinition(TestBean.class)
			.addPropertyValue("name", "@<key1>")
			.addPropertyValue("sex", "${key2}")
			.getBeanDefinition());

	System.setProperty("key1", "systemKey1Value");
	System.setProperty("key2", "systemKey2Value");
	ppc.setEnvironment(new StandardEnvironment());
	ppc.postProcessBeanFactory(bf);
	System.clearProperty("key1");
	System.clearProperty("key2");

	assertThat(bf.getBean(TestBean.class).getName(), is("systemKey1Value"));
	assertThat(bf.getBean(TestBean.class).getSex(), is("${key2}"));
}
 
源代码6 项目: iaf   文件: IbisApplicationInitializer.java
@Override
protected WebApplicationContext createWebApplicationContext(ServletContext servletContext) {
	System.setProperty(EndpointImpl.CHECK_PUBLISH_ENDPOINT_PERMISSON_PROPERTY_WITH_SECURITY_MANAGER, "false");
	servletContext.log("Starting IBIS WebApplicationInitializer");

	XmlWebApplicationContext applicationContext = new XmlWebApplicationContext();
	applicationContext.setConfigLocation(XmlWebApplicationContext.CLASSPATH_URL_PREFIX + "/webApplicationContext.xml");
	applicationContext.setDisplayName("IbisApplicationInitializer");

	MutablePropertySources propertySources = applicationContext.getEnvironment().getPropertySources();
	propertySources.remove(StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME);
	propertySources.remove(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME);
	propertySources.addFirst(new PropertiesPropertySource("ibis", AppConstants.getInstance()));

	return applicationContext;
}
 
/**
 * Create a new AbstractBeanDefinitionReader for the given bean factory.
 * <p>If the passed-in bean factory does not only implement the BeanDefinitionRegistry
 * interface but also the ResourceLoader interface, it will be used as default
 * ResourceLoader as well. This will usually be the case for
 * {@link org.springframework.context.ApplicationContext} implementations.
 * <p>If given a plain BeanDefinitionRegistry, the default ResourceLoader will be a
 * {@link org.springframework.core.io.support.PathMatchingResourcePatternResolver}.
 * <p>If the passed-in bean factory also implements {@link EnvironmentCapable} its
 * environment will be used by this reader.  Otherwise, the reader will initialize and
 * use a {@link StandardEnvironment}. All ApplicationContext implementations are
 * EnvironmentCapable, while normal BeanFactory implementations are not.
 * @param registry the BeanFactory to load bean definitions into,
 * in the form of a BeanDefinitionRegistry
 * @see #setResourceLoader
 * @see #setEnvironment
 */
protected AbstractBeanDefinitionReader(BeanDefinitionRegistry registry) {
	Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
	this.registry = registry;

	// Determine ResourceLoader to use.
	if (this.registry instanceof ResourceLoader) {
		this.resourceLoader = (ResourceLoader) this.registry;
	}
	else {
		this.resourceLoader = new PathMatchingResourcePatternResolver();
	}

	// Inherit Environment if possible
	if (this.registry instanceof EnvironmentCapable) {
		this.environment = ((EnvironmentCapable) this.registry).getEnvironment();
	}
	else {
		this.environment = new StandardEnvironment();
	}
}
 
@Test
public void getBean_withActiveProfile() {
	ConfigurableEnvironment env = new StandardEnvironment();
	env.setActiveProfiles("dev");

	DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
	XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(bf);
	reader.setEnvironment(env);
	reader.loadBeanDefinitions(XML);

	bf.getBean("devOnlyBean"); // should not throw NSBDE

	Object foo = bf.getBean("foo");
	assertThat(foo, instanceOf(Integer.class));

	bf.getBean("devOnlyBean");
}
 
protected final AbstractBeanDefinition createSqlSessionFactoryBean(String dataSourceName, String mapperPackage,
		String typeAliasesPackage, Dialect dialect, Configuration configuration) {
	configuration.setDatabaseId(dataSourceName);
	BeanDefinitionBuilder bdb = BeanDefinitionBuilder.rootBeanDefinition(SqlSessionFactoryBean.class);
	bdb.addPropertyValue("configuration", configuration);
	bdb.addPropertyValue("failFast", true);
	bdb.addPropertyValue("typeAliases", this.saenTypeAliases(typeAliasesPackage));
	bdb.addPropertyReference("dataSource", dataSourceName);
	bdb.addPropertyValue("plugins", new Interceptor[] { new CustomPageInterceptor(dialect) });
	if (!StringUtils.isEmpty(mapperPackage)) {
		try {
			mapperPackage = new StandardEnvironment().resolveRequiredPlaceholders(mapperPackage);
			String mapperPackages = ClassUtils.convertClassNameToResourcePath(mapperPackage);
			String mapperPackagePath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + mapperPackages + "/*.xml";
			Resource[] resources = new PathMatchingResourcePatternResolver().getResources(mapperPackagePath);
			bdb.addPropertyValue("mapperLocations", resources);
		} catch (Exception e) {
			log.error("初始化失败", e);
			throw new RuntimeException( String.format("SqlSessionFactory 初始化失败  mapperPackage=%s", mapperPackage + ""));
		}
	}
	return bdb.getBeanDefinition();
}
 
源代码10 项目: blog_demos   文件: AbstractBeanDefinitionReader.java
/**
 * Create a new AbstractBeanDefinitionReader for the given bean factory.
 * <p>If the passed-in bean factory does not only implement the BeanDefinitionRegistry
 * interface but also the ResourceLoader interface, it will be used as default
 * ResourceLoader as well. This will usually be the case for
 * {@link org.springframework.context.ApplicationContext} implementations.
 * <p>If given a plain BeanDefinitionRegistry, the default ResourceLoader will be a
 * {@link PathMatchingResourcePatternResolver}.
 * <p>If the the passed-in bean factory also implements {@link EnvironmentCapable} its
 * environment will be used by this reader.  Otherwise, the reader will initialize and
 * use a {@link StandardEnvironment}. All ApplicationContext implementations are
 * EnvironmentCapable, while normal BeanFactory implementations are not.
 * @param registry the BeanFactory to load bean definitions into,
 * in the form of a BeanDefinitionRegistry
 * @see #setResourceLoader
 * @see #setEnvironment
 */
protected AbstractBeanDefinitionReader(BeanDefinitionRegistry registry) {
	Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
	this.registry = registry;

	// Determine ResourceLoader to use.
	if (this.registry instanceof ResourceLoader) {
		this.resourceLoader = (ResourceLoader) this.registry;
	}
	else {
		this.resourceLoader = new PathMatchingResourcePatternResolver();
	}

	// Inherit Environment if possible
	if (this.registry instanceof EnvironmentCapable) {
		this.environment = ((EnvironmentCapable) this.registry).getEnvironment();
	}
	else {
		this.environment = new StandardEnvironment();
	}
}
 
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
    StandardEnvironment environment = (StandardEnvironment) beanFactory.getBean(Environment.class);

    Map<String, Object> systemEnvironment = environment.getSystemEnvironment();
    Map<String, Object> prefixlessSystemEnvironment = new HashMap<>(systemEnvironment.size());
    systemEnvironment
            .keySet()
            .forEach(key -> {
                String prefixKey = key;
                for (String propertyPrefix : PROPERTY_PREFIXES) {
                    if (key.startsWith(propertyPrefix)) {
                        prefixKey = key.substring(propertyPrefix.length());
                        break;
                    }
                }
                prefixlessSystemEnvironment.put(prefixKey, systemEnvironment.get(key));
            });
    environment.getPropertySources().replace(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME,
            new RelaxedPropertySource(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, prefixlessSystemEnvironment));
}
 
@Test
public void testDefaultLabel() {
	ConfigServerProperties props = new ConfigServerProperties();
	props.setDefaultLabel("mylabel");
	NativeEnvironmentRepositoryFactory factory = new NativeEnvironmentRepositoryFactory(
			new StandardEnvironment(), props);
	NativeEnvironmentProperties environmentProperties = new NativeEnvironmentProperties();
	NativeEnvironmentRepository repo = factory.build(environmentProperties);
	assertThat(repo.getDefaultLabel()).isEqualTo("mylabel");

	factory = new NativeEnvironmentRepositoryFactory(new StandardEnvironment(),
			props);
	environmentProperties = new NativeEnvironmentProperties();
	environmentProperties.setDefaultLabel("mynewlabel");
	repo = factory.build(environmentProperties);
	assertThat(repo.getDefaultLabel()).isEqualTo("mylabel");

	factory = new NativeEnvironmentRepositoryFactory(new StandardEnvironment(),
			new ConfigServerProperties());
	environmentProperties = new NativeEnvironmentProperties();
	environmentProperties.setDefaultLabel("mynewlabel");
	repo = factory.build(environmentProperties);
	assertThat(repo.getDefaultLabel()).isEqualTo("mynewlabel");
}
 
public void loadConfig() {
	Properties globalProperties = buildGlobalNacosProperties();
	MutablePropertySources mutablePropertySources = environment.getPropertySources();
	List<NacosPropertySource> sources = reqGlobalNacosConfig(globalProperties,
			nacosConfigProperties.getType());
	for (NacosConfigProperties.Config config : nacosConfigProperties.getExtConfig()) {
		List<NacosPropertySource> elements = reqSubNacosConfig(config,
				globalProperties, config.getType());
		sources.addAll(elements);
	}
	if (nacosConfigProperties.isRemoteFirst()) {
		for (ListIterator<NacosPropertySource> itr = sources.listIterator(sources.size()); itr.hasPrevious();) {
			mutablePropertySources.addAfter(
					StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, itr.previous());
		}
	} else {
		for (NacosPropertySource propertySource : sources) {
			mutablePropertySources.addLast(propertySource);
		}
	}
}
 
源代码14 项目: syndesis   文件: SyndesisCommand.java
private AbstractApplicationContext createContext() {
    final AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();

    final YamlPropertySourceLoader propertySourceLoader = new YamlPropertySourceLoader();
    final List<PropertySource<?>> yamlPropertySources;
    try {
        yamlPropertySources = propertySourceLoader.load(name, context.getResource("classpath:" + name + ".yml"));
    } catch (final IOException e) {
        throw new IllegalStateException(e);
    }

    final StandardEnvironment environment = new StandardEnvironment();
    final MutablePropertySources propertySources = environment.getPropertySources();
    propertySources.addFirst(new MapPropertySource("parameters", parameters));
    yamlPropertySources.forEach(propertySources::addLast);

    context.setEnvironment(environment);

    final String packageName = getClass().getPackage().getName();
    context.scan(packageName);

    context.refresh();

    return context;
}
 
/**
 * Get the Environment from the given registry if possible, otherwise return a new
 * StandardEnvironment.
 */
private static Environment getOrCreateEnvironment(BeanDefinitionRegistry registry) {
	Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
	if (registry instanceof EnvironmentCapable) {
		return ((EnvironmentCapable) registry).getEnvironment();
	}
	return new StandardEnvironment();
}
 
/**
 * Get the Environment from the given registry if possible, otherwise return a new
 * StandardEnvironment.
 */
private static Environment getOrCreateEnvironment(BeanDefinitionRegistry registry) {
	Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
	if (registry instanceof EnvironmentCapable) {
		return ((EnvironmentCapable) registry).getEnvironment();
	}
	return new StandardEnvironment();
}
 
源代码17 项目: spring-data-dev-tools   文件: HttpResultsWriter.java
private void doWrite(Collection<RunResult> results) throws IOException {

		StandardEnvironment env = new StandardEnvironment();

		String projectVersion = env.getProperty("project.version", "unknown");
		String gitBranch = env.getProperty("git.branch", "unknown");
		String gitDirty = env.getProperty("git.dirty", "no");
		String gitCommitId = env.getProperty("git.commit.id", "unknown");

		HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
		connection.setConnectTimeout((int) Duration.ofSeconds(1).toMillis());
		connection.setReadTimeout((int) Duration.ofSeconds(1).toMillis());
		connection.setDoOutput(true);
		connection.setRequestMethod("POST");

		connection.setRequestProperty("Content-Type", "application/json");
		connection.addRequestProperty("X-Project-Version", projectVersion);
		connection.addRequestProperty("X-Git-Branch", gitBranch);
		connection.addRequestProperty("X-Git-Dirty", gitDirty);
		connection.addRequestProperty("X-Git-Commit-Id", gitCommitId);

		try (OutputStream output = connection.getOutputStream()) {
			output.write(ResultsWriter.jsonifyResults(results).getBytes(StandardCharsets.UTF_8));
		}

		if (connection.getResponseCode() >= 400) {
			throw new IllegalStateException(
					String.format("Status %d %s", connection.getResponseCode(), connection.getResponseMessage()));
		}
	}
 
@Test
public void disabledPropertySourceAvoidChecks() throws IOException {
	when(this.gcpConfigProperties.isEnabled()).thenReturn(false);
	this.googleConfigPropertySourceLocator =
			spy(new GoogleConfigPropertySourceLocator(null, null, this.gcpConfigProperties));
	this.googleConfigPropertySourceLocator.locate(new StandardEnvironment());
	verify(this.googleConfigPropertySourceLocator, never()).getRemoteEnvironment();
}
 
@Override
protected ConfigurationClassParser newParser() {
	return new ConfigurationClassParser(
			new CachingMetadataReaderFactory(),
			new FailFastProblemReporter(),
			new StandardEnvironment(),
			new DefaultResourceLoader(),
			new AnnotationBeanNameGenerator(),
			new DefaultListableBeanFactory());
}
 
@Test
public void testWithInactiveProfile() {
	ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(true);
	ConfigurableEnvironment env = new StandardEnvironment();
	env.setActiveProfiles("other");
	provider.setEnvironment(env);
	Set<BeanDefinition> candidates = provider.findCandidateComponents(TEST_PROFILE_PACKAGE);
	assertThat(containsBeanClass(candidates, ProfileAnnotatedComponent.class), is(false));
}
 
@Test
public void testWithActiveProfile() {
	ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(true);
	ConfigurableEnvironment env = new StandardEnvironment();
	env.setActiveProfiles(ProfileAnnotatedComponent.PROFILE_NAME);
	provider.setEnvironment(env);
	Set<BeanDefinition> candidates = provider.findCandidateComponents(TEST_PROFILE_PACKAGE);
	assertThat(containsBeanClass(candidates, ProfileAnnotatedComponent.class), is(true));
}
 
/**
 * Get the Environment from the given registry if possible, otherwise return a new
 * StandardEnvironment.
 */
private static Environment getOrCreateEnvironment(BeanDefinitionRegistry registry) {
	Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
	if (registry instanceof EnvironmentCapable) {
		return ((EnvironmentCapable) registry).getEnvironment();
	}
	return new StandardEnvironment();
}
 
@Test(expected = IllegalArgumentException.class)
public void testStrictSystemPropertyReplacement() {
	PropertyEditor editor = new ResourceArrayPropertyEditor(
			new PathMatchingResourcePatternResolver(), new StandardEnvironment(),
			false);
	System.setProperty("test.prop", "foo");
	try {
		editor.setAsText("${test.prop}-${bar}");
		Resource[] resources = (Resource[]) editor.getValue();
		assertEquals("foo-${bar}", resources[0].getFilename());
	}
	finally {
		System.getProperties().remove("test.prop");
	}
}
 
源代码24 项目: spring-analysis-note   文件: ResourceEditorTests.java
@Test(expected = IllegalArgumentException.class)
public void testStrictSystemPropertyReplacement() {
	PropertyEditor editor = new ResourceEditor(new DefaultResourceLoader(), new StandardEnvironment(), false);
	System.setProperty("test.prop", "foo");
	try {
		editor.setAsText("${test.prop}-${bar}");
		Resource resolved = (Resource) editor.getValue();
		assertEquals("foo-${bar}", resolved.getFilename());
	}
	finally {
		System.getProperties().remove("test.prop");
	}
}
 
@Test
public void locateReturnsMapPropertySource() throws Exception {
	GoogleConfigEnvironment googleConfigEnvironment = mock(GoogleConfigEnvironment.class);
	when(googleConfigEnvironment.getConfig()).thenReturn(this.expectedProperties);
	this.googleConfigPropertySourceLocator = spy(new GoogleConfigPropertySourceLocator(
			this.projectIdProvider, this.credentialsProvider, this.gcpConfigProperties));
	doReturn(googleConfigEnvironment).when(this.googleConfigPropertySourceLocator).getRemoteEnvironment();
	PropertySource<?> propertySource = this.googleConfigPropertySourceLocator.locate(new StandardEnvironment());
	assertThat(propertySource.getName()).isEqualTo("spring-cloud-gcp");
	assertThat(propertySource.getProperty("property-int")).isEqualTo(10);
	assertThat(propertySource.getProperty("property-bool")).isEqualTo(true);
	assertThat(this.googleConfigPropertySourceLocator.getProjectId()).isEqualTo("projectid");
}
 
@Test
public void setAllProperties() {
	this.contextRunner
	.withInitializer(context -> {
		Map<String, Object> map = new HashMap<>();
		map.put("spring.cloud.deployer.cloudfoundry.org", "org");
		map.put("spring.cloud.deployer.cloudfoundry.space", "space");
		map.put("spring.cloud.deployer.cloudfoundry.url", "http://example.com");
		map.put("spring.cloud.deployer.cloudfoundry.username", "username");
		map.put("spring.cloud.deployer.cloudfoundry.password", "password");
		map.put("spring.cloud.deployer.cloudfoundry.client-id", "id");
		map.put("spring.cloud.deployer.cloudfoundry.client-secret", "secret");
		map.put("spring.cloud.deployer.cloudfoundry.login-hint", "hint");
		map.put("spring.cloud.deployer.cloudfoundry.skip-ssl-validation", "true");
		context.getEnvironment().getPropertySources().addLast(new SystemEnvironmentPropertySource(
			StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, map));
		})
		.withUserConfiguration(Config1.class)
		.run((context) -> {
			CloudFoundryConnectionProperties properties = context.getBean(CloudFoundryConnectionProperties.class);
			assertThat(properties.getOrg()).isEqualTo("org");
			assertThat(properties.getSpace()).isEqualTo("space");
			assertThat(properties.getUrl().toString()).isEqualTo("http://example.com");
			assertThat(properties.getUsername()).isEqualTo("username");
			assertThat(properties.getPassword()).isEqualTo("password");
			assertThat(properties.getClientId()).isEqualTo("id");
			assertThat(properties.getClientSecret()).isEqualTo("secret");
			assertThat(properties.getLoginHint()).isEqualTo("hint");
			assertThat(properties.isSkipSslValidation()).isTrue();
		});
}
 
@Test
public void testParentExecutionId() {
	ConfigurableEnvironment environment = new StandardEnvironment();
	MutablePropertySources propertySources = environment.getPropertySources();
	Map<String, Object> myMap = new HashMap<>();
	myMap.put("spring.cloud.task.parentExecutionId", 789);
	propertySources
			.addFirst(new MapPropertySource("EnvrionmentTestPropsource", myMap));
	this.context.setEnvironment(environment);
	this.context.refresh();
	this.taskExplorer = this.context.getBean(TaskExplorer.class);

	verifyTaskExecution(0, false, null, null, null, 789L);
}
 
private BeanDefinitionRegistry beanFactoryFor(String xmlName, String... activeProfiles) {
	DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
	XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(beanFactory);
	StandardEnvironment env = new StandardEnvironment();
	env.setActiveProfiles(activeProfiles);
	reader.setEnvironment(env);
	reader.loadBeanDefinitions(new ClassPathResource(xmlName, getClass()));
	return beanFactory;
}
 
源代码29 项目: pmq   文件: MqEnvProp.java
private Map<String, PropertySource<?>> getPropertySources() {
	Map<String, PropertySource<?>> map = new LinkedHashMap<String, PropertySource<?>>();
	MutablePropertySources sources = null;		
	if (environment != null && environment instanceof ConfigurableEnvironment) {
		sources = ((ConfigurableEnvironment) environment).getPropertySources();
	}
	else {
		sources = new StandardEnvironment().getPropertySources();
	}
	for (PropertySource<?> source : sources) {
		extract("", map, source);
	}
	return map;
}
 
源代码30 项目: metacat   文件: SpringConnectorFactory.java
/**
 * Constructor.
 *
 * @param connectorInfoConverter connector info converter
 * @param connectorContext       connector related config
 */
public SpringConnectorFactory(final ConnectorInfoConverter connectorInfoConverter,
                              final ConnectorContext connectorContext) {
    this.catalogName = connectorContext.getCatalogName();
    this.catalogShardName = connectorContext.getCatalogShardName();
    this.ctx = new AnnotationConfigApplicationContext();
    this.ctx.setEnvironment(new StandardEnvironment());
    this.ctx.getBeanFactory().registerSingleton("ConnectorContext", connectorContext);
    this.ctx.getBeanFactory().registerSingleton("ConnectorInfoConverter", connectorInfoConverter);
}