org.springframework.core.env.StandardEnvironment Java Examples

The following examples show how to use org.springframework.core.env.StandardEnvironment. 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: DSSSpringApplication.java    From DataSphereStudio with Apache License 2.0 6 votes vote down vote up
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());
        }
    }
}
 
Example #2
Source File: PropertySourcesPlaceholderConfigurerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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}"));
}
 
Example #3
Source File: AbstractBeanDefinitionReader.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * 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();
	}
}
 
Example #4
Source File: NestedBeansElementTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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");
}
 
Example #5
Source File: EnvironmentBeanFactoryPostProcessor.java    From gravitee-management-rest-api with Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example #6
Source File: IbisApplicationInitializer.java    From iaf with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #7
Source File: AbstractDataBaseBean.java    From spring-boot-starter-dao with Apache License 2.0 6 votes vote down vote up
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();
}
 
Example #8
Source File: NativeEnvironmentRepositoryFactoryTest.java    From spring-cloud-config with Apache License 2.0 6 votes vote down vote up
@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");
}
 
Example #9
Source File: DataSourceMapSetterTest.java    From shardingsphere with Apache License 2.0 6 votes vote down vote up
@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"));
}
 
Example #10
Source File: SyndesisCommand.java    From syndesis with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #11
Source File: NestedBeansElementTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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");
}
 
Example #12
Source File: NacosConfigLoader.java    From nacos-spring-boot-project with Apache License 2.0 6 votes vote down vote up
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);
		}
	}
}
 
Example #13
Source File: AbstractBeanDefinitionReader.java    From blog_demos with Apache License 2.0 6 votes vote down vote up
/**
 * 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();
	}
}
 
Example #14
Source File: PropertySourcesPlaceholderConfigurerTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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}"));
}
 
Example #15
Source File: WebSocketDocsTest.java    From chassis with Apache License 2.0 5 votes vote down vote up
@Test
public void testProtobufMessagesEnvelope() throws Exception {
	Map<String, Object> properties = new HashMap<String, Object>();
	properties.put("admin.enabled", "true");
	properties.put("admin.port", "" + SocketUtils.findAvailableTcpPort());
	properties.put("admin.hostname", "localhost");
	
	properties.put("websocket.enabled", "true");
	properties.put("websocket.port", "" + SocketUtils.findAvailableTcpPort());
	properties.put("websocket.hostname", "localhost");

	properties.put("http.enabled", "false");
	
	AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
	StandardEnvironment environment = new StandardEnvironment();
	environment.getPropertySources().addFirst(new MapPropertySource("default", properties));
	context.setEnvironment(environment);
	context.register(PropertySourcesPlaceholderConfigurer.class);
	context.register(TransportConfiguration.class);

	RestTemplate httpClient = new RestTemplate();
	
	try {
		context.refresh();

		httpClient.setInterceptors(Lists.newArrayList(LOGGING_INTERCEPTOR));

		ResponseEntity<String> response = httpClient.getForEntity(
				new URI("http://localhost:" + properties.get("admin.port") + "/schema/envelope/protobuf"), String.class);
		
		logger.info("Got response: [{}]", response);
		
		Assert.assertEquals(response.getStatusCode().value(), HttpStatus.OK.value());
		Assert.assertTrue(response.getBody().contains("message Envelope"));
	} finally {
		context.close();
	}
}
 
Example #16
Source File: MongoResultsWriter.java    From spring-data-dev-tools with Apache License 2.0 5 votes vote down vote up
private void doWrite(Collection<RunResult> results) throws ParseException {

		Date now = new Date();
		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");

		ConnectionString uri = new ConnectionString(this.uri);
		MongoClient client = MongoClients.create();

		String dbName = StringUtils.hasText(uri.getDatabase()) ? uri.getDatabase() : "spring-data-mongodb-benchmarks";
		MongoDatabase db = client.getDatabase(dbName);

		String resultsJson = ResultsWriter.jsonifyResults(results).trim();
		JSONArray array = (JSONArray) new JSONParser(JSONParser.MODE_PERMISSIVE).parse(resultsJson);
		for (Object object : array) {
			JSONObject dbo = (JSONObject) object;

			String collectionName = extractClass(dbo.get("benchmark").toString());

			Document sink = new Document();
			sink.append("_version", projectVersion);
			sink.append("_branch", gitBranch);
			sink.append("_commit", gitCommitId);
			sink.append("_dirty", gitDirty);
			sink.append("_method", extractBenchmarkName(dbo.get("benchmark").toString()));
			sink.append("_date", now);
			sink.append("_snapshot", projectVersion.toLowerCase().contains("snapshot"));

			sink.putAll(dbo);

			db.getCollection(collectionName).insertOne(fixDocumentKeys(sink));
		}

		client.close();
	}
 
Example #17
Source File: ResourceArrayPropertyEditorTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@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");
	}
}
 
Example #18
Source File: LoggingRebinderTests.java    From spring-cloud-commons with Apache License 2.0 5 votes vote down vote up
@Test
public void logLevelsChanged() {
	then(this.logger.isTraceEnabled()).isFalse();
	StandardEnvironment environment = new StandardEnvironment();
	TestPropertyValues.of("logging.level.org.springframework.web=TRACE")
			.applyTo(environment);
	this.rebinder.setEnvironment(environment);
	this.rebinder.onApplicationEvent(new EnvironmentChangeEvent(environment,
			Collections.singleton("logging.level.org.springframework.web")));
	then(this.logger.isTraceEnabled()).isTrue();
}
 
Example #19
Source File: ApacheCommonsConfigurationPropertySource.java    From Spring-Boot-2.0-Cookbook-Second-Edition with MIT License 5 votes vote down vote up
public static void addToEnvironment(ConfigurableEnvironment environment,
                                    XMLConfiguration xmlConfiguration) {
    environment.getPropertySources().addAfter(
            StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME,
            new ApacheCommonsConfigurationPropertySource(
                    COMMONS_CONFIG_PROPERTY_SOURCE_NAME, xmlConfiguration));
    logger.trace("ApacheCommonsConfigurationPropertySource add to Environment");
}
 
Example #20
Source File: ResourceEditorTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@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");
	}
}
 
Example #21
Source File: ClassPathScanningCandidateComponentProvider.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public final Environment getEnvironment() {
	if (this.environment == null) {
		this.environment = new StandardEnvironment();
	}
	return this.environment;
}
 
Example #22
Source File: ConfigurationClassPostProcessorTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
private void assertSupportForComposedAnnotationWithExclude(RootBeanDefinition beanDefinition) {
	beanFactory.registerBeanDefinition("config", beanDefinition);
	ConfigurationClassPostProcessor pp = new ConfigurationClassPostProcessor();
	pp.setEnvironment(new StandardEnvironment());
	pp.postProcessBeanFactory(beanFactory);
	try {
		beanFactory.getBean(SimpleComponent.class);
		fail("Should have thrown NoSuchBeanDefinitionException");
	}
	catch (NoSuchBeanDefinitionException ex) {
		// expected
	}
}
 
Example #23
Source File: NetstrapBootApplication.java    From netstrap with Apache License 2.0 5 votes vote down vote up
/**
 * 装配Spring容器
 */
private ConfigurableApplicationContext run(String[] configLocations) {
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    NetstrapSpringRunListeners listeners = getRunListener();
    /**
     * starting事件表明,Spring容器将会进行初始化,在此之前,我们可以做一些事情
     * 比如注册一些类型转换器:ConvertUtils.register(Converter converter, Class<?> clazz)
     */
    listeners.starting();
    try {

        //创建上下文
        context = createApplicationContext(configLocations);
        //准备Context
        prepareContext(context, new StandardEnvironment());
        //Spring容器初始化完毕(包括引入的Spring组件)之后调用
        listeners.contextPrepare(context);
        //启动网络服务
        networkServiceStartup(context);
        //停止监控
        stopWatch.stop();
        //Spring容器初始化完毕并且启动网络服务之后调用
        listeners.started(context);
        //开始监听请求
        server.join();
    } catch (Throwable ex) {
        ex.printStackTrace();
        context.close();
        if (server.isStarted()) {
            server.stop();
        }
        handleRunFailure(context, ex, listeners);
    }

    return context;
}
 
Example #24
Source File: EnvProp.java    From radar with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #25
Source File: ResourceArrayPropertyEditorTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@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");
	}
}
 
Example #26
Source File: ClassPathScanningCandidateComponentProviderTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@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));
}
 
Example #27
Source File: ClassPathScanningCandidateComponentProviderTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@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));
}
 
Example #28
Source File: TaskStartTests.java    From spring-cloud-task with Apache License 2.0 5 votes vote down vote up
private SpringApplication getTaskApplication(Integer executionId) {
	SpringApplication myapp = new SpringApplication(TaskStartApplication.class);
	Map<String, Object> myMap = new HashMap<>();
	ConfigurableEnvironment environment = new StandardEnvironment();
	MutablePropertySources propertySources = environment.getPropertySources();
	myMap.put("spring.cloud.task.executionid", executionId);
	propertySources
			.addFirst(new MapPropertySource("EnvrionmentTestPropsource", myMap));
	myapp.setEnvironment(environment);
	return myapp;
}
 
Example #29
Source File: TaskLifecycleListenerTests.java    From spring-cloud-task with Apache License 2.0 5 votes vote down vote up
@Test
public void testExternalExecutionId() {
	ConfigurableEnvironment environment = new StandardEnvironment();
	MutablePropertySources propertySources = environment.getPropertySources();
	Map<String, Object> myMap = new HashMap<>();
	myMap.put("spring.cloud.task.external-execution-id", "myid");
	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, "myid");
}
 
Example #30
Source File: ContextRefresher.java    From spring-cloud-commons with Apache License 2.0 5 votes vote down vote up
private StandardEnvironment copyEnvironment(ConfigurableEnvironment input) {
	StandardEnvironment environment = new StandardEnvironment();
	MutablePropertySources capturedPropertySources = environment.getPropertySources();
	// Only copy the default property source(s) and the profiles over from the main
	// environment (everything else should be pristine, just like it was on startup).
	for (String name : DEFAULT_PROPERTY_SOURCES) {
		if (input.getPropertySources().contains(name)) {
			if (capturedPropertySources.contains(name)) {
				capturedPropertySources.replace(name,
						input.getPropertySources().get(name));
			}
			else {
				capturedPropertySources.addLast(input.getPropertySources().get(name));
			}
		}
	}
	environment.setActiveProfiles(input.getActiveProfiles());
	environment.setDefaultProfiles(input.getDefaultProfiles());
	Map<String, Object> map = new HashMap<String, Object>();
	map.put("spring.jmx.enabled", false);
	map.put("spring.main.sources", "");
	// gh-678 without this apps with this property set to REACTIVE or SERVLET fail
	map.put("spring.main.web-application-type", "NONE");
	capturedPropertySources
			.addFirst(new MapPropertySource(REFRESH_ARGS_PROPERTY_SOURCE, map));
	return environment;
}