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

项目:azure-spring-boot    文件:KeyVaultEnvironmentPostProcessorHelper.java   
public void addKeyVaultPropertySource() {
    final String clientId = getProperty(environment, Constants.AZURE_CLIENTID);
    final String clientKey = getProperty(environment, Constants.AZURE_CLIENTKEY);
    final String vaultUri = getProperty(environment, Constants.AZURE_KEYVAULT_VAULT_URI);

    final long timeAcquiringTimeoutInSeconds = environment.getProperty(
            Constants.AZURE_TOKEN_ACQUIRE_TIMEOUT_IN_SECONDS, Long.class, 60L);

    final KeyVaultClient kvClient = new KeyVaultClient(
            new AzureKeyVaultCredential(clientId, clientKey, timeAcquiringTimeoutInSeconds));

    try {
        final MutablePropertySources sources = environment.getPropertySources();
        final KeyVaultOperation kvOperation = new KeyVaultOperation(kvClient, vaultUri);

        if (sources.contains(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME)) {
            sources.addAfter(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME,
                    new KeyVaultPropertySource(kvOperation));
        } else {
            sources.addFirst(new KeyVaultPropertySource(kvOperation));
        }

    } catch (Exception ex) {
        throw new IllegalStateException("Failed to configure KeyVault property source", ex);
    }
}
项目:lams    文件: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 org.springframework.core.io.support.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();
    }
}
项目:spring-boot-starter-dao    文件:AbstractDataBaseBean.java   
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();
}
项目:spring4-understanding    文件:PropertySourcesPlaceholderConfigurerTests.java   
@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}"));
}
项目:spring4-understanding    文件: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 org.springframework.core.io.support.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();
    }
}
项目:spring4-understanding    文件:NestedBeansElementTests.java   
@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");
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:SpringApplicationBindContextLoader.java   
@Override
public ApplicationContext loadContext(MergedContextConfiguration config)
        throws Exception {
    SpringApplication application = new SpringApplication();
    application.setMainApplicationClass(config.getTestClass());
    application.setWebEnvironment(false);
    application.setSources(
            new LinkedHashSet<Object>(Arrays.asList(config.getClasses())));
    ConfigurableEnvironment environment = new StandardEnvironment();
    Map<String, Object> properties = new LinkedHashMap<String, Object>();
    properties.put("spring.jmx.enabled", "false");
    properties.putAll(TestPropertySourceUtils
            .convertInlinedPropertiesToMap(config.getPropertySourceProperties()));
    environment.getPropertySources().addAfter(
            StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME,
            new MapPropertySource("integrationTest", properties));
    application.setEnvironment(environment);
    return application.run();
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:SpringApplicationContextLoader.java   
@Override
public ApplicationContext loadContext(final MergedContextConfiguration config)
        throws Exception {
    assertValidAnnotations(config.getTestClass());
    SpringApplication application = getSpringApplication();
    application.setMainApplicationClass(config.getTestClass());
    application.setSources(getSources(config));
    ConfigurableEnvironment environment = new StandardEnvironment();
    if (!ObjectUtils.isEmpty(config.getActiveProfiles())) {
        setActiveProfiles(environment, config.getActiveProfiles());
    }
    Map<String, Object> properties = getEnvironmentProperties(config);
    addProperties(environment, properties);
    application.setEnvironment(environment);
    List<ApplicationContextInitializer<?>> initializers = getInitializers(config,
            application);
    if (config instanceof WebMergedContextConfiguration) {
        new WebConfigurer().configure(config, application, initializers);
    }
    else {
        application.setWebEnvironment(false);
    }
    application.setInitializers(initializers);
    ConfigurableApplicationContext applicationContext = application.run();
    return applicationContext;
}
项目:spring    文件: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 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();
    }
}
项目:spring-boot-concourse    文件:SpringApplicationBindContextLoader.java   
@Override
public ApplicationContext loadContext(MergedContextConfiguration config)
        throws Exception {
    SpringApplication application = new SpringApplication();
    application.setMainApplicationClass(config.getTestClass());
    application.setWebEnvironment(false);
    application.setSources(
            new LinkedHashSet<Object>(Arrays.asList(config.getClasses())));
    ConfigurableEnvironment environment = new StandardEnvironment();
    Map<String, Object> properties = new LinkedHashMap<String, Object>();
    properties.put("spring.jmx.enabled", "false");
    properties.putAll(TestPropertySourceUtils
            .convertInlinedPropertiesToMap(config.getPropertySourceProperties()));
    environment.getPropertySources().addAfter(
            StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME,
            new MapPropertySource("integrationTest", properties));
    application.setEnvironment(environment);
    return application.run();
}
项目:spring-boot-concourse    文件:SpringApplicationContextLoader.java   
@Override
public ApplicationContext loadContext(final MergedContextConfiguration config)
        throws Exception {
    assertValidAnnotations(config.getTestClass());
    SpringApplication application = getSpringApplication();
    application.setMainApplicationClass(config.getTestClass());
    application.setSources(getSources(config));
    ConfigurableEnvironment environment = new StandardEnvironment();
    if (!ObjectUtils.isEmpty(config.getActiveProfiles())) {
        setActiveProfiles(environment, config.getActiveProfiles());
    }
    Map<String, Object> properties = getEnvironmentProperties(config);
    addProperties(environment, properties);
    application.setEnvironment(environment);
    List<ApplicationContextInitializer<?>> initializers = getInitializers(config,
            application);
    if (config instanceof WebMergedContextConfiguration) {
        new WebConfigurer().configure(config, application, initializers);
    }
    else {
        application.setWebEnvironment(false);
    }
    application.setInitializers(initializers);
    ConfigurableApplicationContext applicationContext = application.run();
    return applicationContext;
}
项目:contestparser    文件:SpringApplicationContextLoader.java   
@Override
public ApplicationContext loadContext(final MergedContextConfiguration config)
        throws Exception {
    assertValidAnnotations(config.getTestClass());
    SpringApplication application = getSpringApplication();
    application.setMainApplicationClass(config.getTestClass());
    application.setSources(getSources(config));
    ConfigurableEnvironment environment = new StandardEnvironment();
    if (!ObjectUtils.isEmpty(config.getActiveProfiles())) {
        setActiveProfiles(environment, config.getActiveProfiles());
    }
    Map<String, Object> properties = getEnvironmentProperties(config);
    addProperties(environment, properties);
    application.setEnvironment(environment);
    List<ApplicationContextInitializer<?>> initializers = getInitializers(config,
            application);
    if (config instanceof WebMergedContextConfiguration) {
        new WebConfigurer().configure(config, application, initializers);
    }
    else {
        application.setWebEnvironment(false);
    }
    application.setInitializers(initializers);
    ConfigurableApplicationContext applicationContext = application.run();
    return applicationContext;
}
项目:eHMP    文件:JMeadowsPatientServiceTest.java   
@Before
public void setup() {
    mockEnvironment = mock(StandardEnvironment.class);

    when(mockEnvironment.getProperty(HmpProperties.JMEADOWS_URL)).thenReturn("test.url");
    when(mockEnvironment.getProperty(HmpProperties.JMEADOWS_TIMEOUT_MS)).thenReturn("45000");
    when(mockEnvironment.getProperty(HmpProperties.JMEADOWS_USER_NAME)).thenReturn("test.username");
    when(mockEnvironment.getProperty(HmpProperties.JMEADOWS_USER_IEN)).thenReturn("test.ien");
    when(mockEnvironment.getProperty(HmpProperties.JMEADOWS_USER_SITE_CODE)).thenReturn("test.sitecode");
    when(mockEnvironment.getProperty(HmpProperties.JMEADOWS_USER_SITE_NAME)).thenReturn("test.sitename");

    JMeadowsConfiguration jMeadowsConfiguration = new JMeadowsConfiguration(mockEnvironment);

    jMeadowsPatientService = new JMeadowsPatientService();
    jMeadowsPatientService.init();
    jMeadowsPatientService.setJMeadowsConfiguration(jMeadowsConfiguration);

}
项目:eHMP    文件:JMeadowsOrderServiceTest.java   
@Before
public void setup() {
    mockEnvironment = mock(StandardEnvironment.class);
    when(mockEnvironment.getProperty(HmpProperties.JMEADOWS_URL)).thenReturn(url);
    when(mockEnvironment.getProperty(HmpProperties.JMEADOWS_TIMEOUT_MS)).thenReturn("" + timeoutMS);
    when(mockEnvironment.getProperty(HmpProperties.JMEADOWS_USER_NAME)).thenReturn(userName);
    when(mockEnvironment.getProperty(HmpProperties.JMEADOWS_USER_IEN)).thenReturn(userIen);
    when(mockEnvironment.getProperty(HmpProperties.JMEADOWS_USER_SITE_CODE)).thenReturn(userSiteCode);
    when(mockEnvironment.getProperty(HmpProperties.JMEADOWS_USER_SITE_NAME)).thenReturn(userSiteName);

    this.mockJMeadowsClient = mock(JMeadowsData.class);
    this.mockJMeadowsOrderService = new JMeadowsOrderService(new JMeadowsConfiguration(mockEnvironment));
    this.mockJMeadowsOrderService.setJMeadowsClient(mockJMeadowsClient);

    user = new User();
    user.setUserIen("test.ien");
    Site hostSite = new Site();
    hostSite.setSiteCode("test.site.code");
    hostSite.setAgency("VA");
    hostSite.setMoniker("test.moniker");
    hostSite.setName("test.site.name");
    user.setHostSite(hostSite);

    patient = new Patient();
    patient.setEDIPI("test.edipi");
}
项目:eHMP    文件:JMeadowsImmunizationServiceTest.java   
@Before
public void setup() {
    mockEnvironment = mock(StandardEnvironment.class);
    when(mockEnvironment.getProperty(HmpProperties.JMEADOWS_URL)).thenReturn(url);
    when(mockEnvironment.getProperty(HmpProperties.JMEADOWS_TIMEOUT_MS)).thenReturn("" + timeoutMS);
    when(mockEnvironment.getProperty(HmpProperties.JMEADOWS_USER_NAME)).thenReturn(userName);
    when(mockEnvironment.getProperty(HmpProperties.JMEADOWS_USER_IEN)).thenReturn(userIen);
    when(mockEnvironment.getProperty(HmpProperties.JMEADOWS_USER_SITE_CODE)).thenReturn(userSiteCode);
    when(mockEnvironment.getProperty(HmpProperties.JMEADOWS_USER_SITE_NAME)).thenReturn(userSiteName);

    this.mockJMeadowsClient = mock(JMeadowsData.class);
    this.jMeadowsImmunizationService = new JMeadowsImmunizationService(new JMeadowsConfiguration(mockEnvironment));
    this.jMeadowsImmunizationService.setJMeadowsClient(mockJMeadowsClient);

    user = new User();
    user.setUserIen("test.ien");
    Site hostSite = new Site();
    hostSite.setSiteCode("test.site.code");
    hostSite.setAgency("VA");
    hostSite.setMoniker("test.moniker");
    hostSite.setName("test.site.name");
    user.setHostSite(hostSite);

    patient = new Patient();
    patient.setEDIPI("test.edipi");
}
项目:eHMP    文件:JMeadowsVitalServiceTest.java   
@Before
public void setup() {
    mockEnvironment = mock(StandardEnvironment.class);
    when(mockEnvironment.getProperty(HmpProperties.JMEADOWS_URL)).thenReturn(url);
    when(mockEnvironment.getProperty(HmpProperties.JMEADOWS_TIMEOUT_MS)).thenReturn("" + timeoutMS);
    when(mockEnvironment.getProperty(HmpProperties.JMEADOWS_USER_NAME)).thenReturn(userName);
    when(mockEnvironment.getProperty(HmpProperties.JMEADOWS_USER_IEN)).thenReturn(userIen);
    when(mockEnvironment.getProperty(HmpProperties.JMEADOWS_USER_SITE_CODE)).thenReturn(userSiteCode);
    when(mockEnvironment.getProperty(HmpProperties.JMEADOWS_USER_SITE_NAME)).thenReturn(userSiteName);

    this.mockJMeadowsClient = mock(JMeadowsData.class);
    this.jMeadowsVitalService = new JMeadowsVitalService(new JMeadowsConfiguration(mockEnvironment));
    this.jMeadowsVitalService.setJMeadowsClient(mockJMeadowsClient);

    user = new User();
    user.setUserIen("test.ien");
    Site hostSite = new Site();
    hostSite.setSiteCode("test.site.code");
    hostSite.setAgency("VA");
    hostSite.setMoniker("test.moniker");
    hostSite.setName("test.site.name");
    user.setHostSite(hostSite);

    patient = new Patient();
    patient.setEDIPI("test.edipi");
}
项目:spring-properties-decrypter    文件:DecryptingPropertiesApplicationListenerTest.java   
@Test
public void shouldWrapExceptionOnEncryptionError() {
    // given
    StandardEnvironment environment = new StandardEnvironment();
    Properties props = new Properties();
    props.put("propertyDecryption.password", "NOT-A-PASSWORD");
    props.put("someProperty", "{encrypted}NOT-ENCRYPTED");
    environment.getPropertySources().addFirst(new PropertiesPropertySource("test-env", props));

    exception.expect(RuntimeException.class);
    exception.expectMessage("Unable to decrypt property value '{encrypted}NOT-ENCRYPTED'");
    exception.expectCause(isA(EncryptionOperationNotPossibleException.class));

    ApplicationEnvironmentPreparedEvent event = new ApplicationEnvironmentPreparedEvent(new SpringApplication(), new String[0], environment);

    // when
    listener.onApplicationEvent(event);

    // then -> exception
}
项目:spring-cloud-commons    文件:ContextRefresher.java   
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", "");
    capturedPropertySources
            .addFirst(new MapPropertySource(REFRESH_ARGS_PROPERTY_SOURCE, map));
    return environment;
}
项目:class-guard    文件:PropertySourcesPlaceholderConfigurerTests.java   
@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}"));
}
项目:class-guard    文件: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 org.springframework.core.io.support.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();
    }
}
项目:class-guard    文件:NestedBeansElementTests.java   
@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");
}
项目:iaf    文件:IbisContext.java   
/**
 * Create Spring Bean factory. Parameter 'springContext' can be null.
 *
 * Create the Spring Bean Factory using the supplied <code>springContext</code>,
 * if not <code>null</code>.
 *
 * @param springContext Spring Context to create. If <code>null</code>,
 * use the default spring context.
 * The spring context is loaded as a spring ClassPathResource from
 * the class path.
 *
 * @return The Spring XML Bean Factory.
 * @throws BeansException If the Factory can not be created.
 *
 */
private ApplicationContext createApplicationContext() throws BeansException {
    // Reading in Spring Context
    long start = System.currentTimeMillis();
    String springContext = "/springContext.xml";
    ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext();
    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", APP_CONSTANTS));
    applicationContext.setConfigLocation(springContext);
    applicationContext.refresh();
    log("startup " + springContext + " in "
            + (System.currentTimeMillis() - start) + " ms");
    return applicationContext;
}
项目:bandwidth-on-demand    文件:AppConfigWebApplicationContext.java   
@Override
protected ConfigurableEnvironment createEnvironment() {
  loadProperties();

  StandardEnvironment env = new StandardEnvironment();

  validateMode(nsiRequesterMode, ImmutableList.of("nsi-requester", "nsi-requester-offline"));
  validateMode(organizationClientMode, ImmutableList.of("kis", "kis-offline"));
  validateMode(vootMode, ImmutableList.of("voot", "voot-offline"));

  env.setActiveProfiles(nsiRequesterMode, organizationClientMode, vootMode);

  if (sslReplies) {
    env.addActiveProfile("stunnel");
  }

  LOGGER.info("Starting with active profiles: {}", Stream.of(env.getActiveProfiles()).collect(joining(", ")));

  return env;
}
项目:NoJPA    文件:Properties.java   
@Test
public void test_01() throws Exception {
    StandardEnvironment env = new StandardEnvironment();

    java.util.Properties props = new java.util.Properties();
    props.setProperty("spring.datasource.driverClassName", "com.mysql.jdbc.Driver");
    props.setProperty("spring.datasource.url", "jdbc:mysql://localhost:3306/reqxldb?useUnicode=true");
    props.setProperty("spring.datasource.username", "root");
    props.setProperty("spring.datasource.password", "1234");
    props.setProperty("spring.datasource.nrOfPoolConnections", "10");

    env.getPropertySources().addFirst(new PropertiesPropertySource("test", props));
    java.util.Properties from = NoJpaDatabaseProperties.from(env);

    Assert.assertEquals(from.getProperty("driverName"), "com.mysql.jdbc.Driver");
    Assert.assertEquals(from.getProperty("user"), "root");
    Assert.assertEquals(from.getProperty("password"), "1234");
    Assert.assertEquals(from.getProperty("nrOfPoolConnections"), "10");
    Assert.assertEquals(from.getProperty("ip"), "localhost");
    Assert.assertEquals(from.getProperty("database"), "mysql");
    Assert.assertEquals(from.getProperty("databaseName"), "reqxldb?useUnicode=true");
    Assert.assertEquals(from.getProperty("port"), "3306");
}
项目:incubator-servicecomb-java-chassis    文件:SpringUtils.java   
public static StringValueResolver createStringValueResolver(Map<String, Object> map) {
  StandardEnvironment standardEnvironment = new StandardEnvironment();
  standardEnvironment.getPropertySources().addFirst(
      new MapPropertySource(UUID.randomUUID().toString(), map));

  return standardEnvironment::resolvePlaceholders;
}
项目:spring-configuration-support    文件:DaoConfigurationPropertiesTest.java   
@Bean(name = "databaseConfigurationSources")
public PropertiesPropertySource[] databaseConfigurationSources(
        @Named("daoConfigurationFactoryBean") OrderedProperties orderedProperties,
        ConfigurableEnvironment environment) throws Exception {

    PropertiesPropertySource[] propertiesPropertySources = orderedProperties.toPropertiesPropertySources();
    for(int i=(propertiesPropertySources.length-1);i>=0;i--){
        environment.getPropertySources().addAfter(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, propertiesPropertySources[i]);
    }
    return propertiesPropertySources;
}
项目:spring-configuration-support    文件:SpringTestContextConfiguration.java   
@Bean(name = "databaseConfigurationSources")
public PropertiesPropertySource[] databaseConfigurationSource(
        @Named("databaseConfigurationFactoryBean") OrderedProperties orderedProperties,
        ConfigurableEnvironment environment) throws Exception {

    PropertiesPropertySource[] propertiesPropertySources = orderedProperties.toPropertiesPropertySources();
    for(int i=(propertiesPropertySources.length-1);i>=0;i--){
        environment.getPropertySources().addAfter(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, propertiesPropertySources[i]);
    }
    return propertiesPropertySources;
}
项目:spring-configuration-support    文件:DefaultsTest.java   
@Bean(name = "source")
public PropertiesPropertySource[] source(
        @Qualifier("props") OrderedProperties orderedProperties,
        ConfigurableEnvironment environment) throws Exception {

    PropertiesPropertySource[] propertiesPropertySources = orderedProperties.toPropertiesPropertySources();
    for(PropertiesPropertySource propertiesPropertySource: propertiesPropertySources){
        environment.getPropertySources().addAfter(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, propertiesPropertySource);
    }
    return propertiesPropertySources;
}
项目:lams    文件:AnnotatedBeanDefinitionReader.java   
/**
 * 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();
}
项目:lams    文件:ClassPathBeanDefinitionScanner.java   
/**
 * 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();
}
项目:spring-cloud-gcp    文件:GoogleConfigPropertySourceLocatorTest.java   
@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());
    assertEquals(propertySource.getName(), "spring-cloud-gcp");
    assertEquals(propertySource.getProperty("property-int"), 10);
    assertEquals(propertySource.getProperty("property-bool"), true);
    assertEquals("projectid", this.googleConfigPropertySourceLocator.getProjectId());
}
项目:spring-cloud-gcp    文件:GoogleConfigPropertySourceLocatorTest.java   
@Test
public void locateReturnsMapPropertySource_disabled() throws Exception {
    when(this.gcpConfigProperties.isEnabled()).thenReturn(false);
    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());
    assertEquals(propertySource.getName(), "spring-cloud-gcp");
    assertEquals(0, ((MapPropertySource) propertySource).getPropertyNames().length);
}
项目:spring-cloud-gcp    文件:GoogleConfigPropertySourceLocatorTest.java   
@Test
public void disabledPropertySourceReturnsNull() throws Exception {
    when(this.gcpConfigProperties.isEnabled()).thenReturn(false);
    this.googleConfigPropertySourceLocator = spy(new GoogleConfigPropertySourceLocator(
            this.projectIdProvider, this.credentialsProvider, this.gcpConfigProperties));
    this.googleConfigPropertySourceLocator.locate(new StandardEnvironment());
    verify(this.googleConfigPropertySourceLocator, never()).getRemoteEnvironment();
}
项目:spring-cloud-gcp    文件:GoogleConfigPropertySourceLocatorTest.java   
@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();
}
项目:springboot-analysis    文件:CustomBeanFactoryPostProcessor.java   
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
    String name = "custom";
    Map<String, Object> map = new HashMap<>();
    map.put("my.name", "processor");
    ((StandardEnvironment) applicationContext.getEnvironment()).getPropertySources().addFirst(new MapPropertySource(name, map));
}
项目:gorm-redis    文件:RedisDatastore.java   
private static PropertyResolver convertToResolver(Map<String, Object> config) {
    if(config instanceof PropertyResolver) {
        return (PropertyResolver) config;
    }
    else {
        StandardEnvironment env = new StandardEnvironment();
        env.getPropertySources().addFirst(new MapPropertySource("datastoreConfig", config));
        return env;
    }
}
项目:metacat    文件:SpringConnectorFactory.java   
/**
 * Constructor.
 *
 * @param catalogName            catalog name
 * @param connectorInfoConverter connector info converter
 * @param connectorContext       connector related config
 */
public SpringConnectorFactory(final String catalogName,
                              final ConnectorInfoConverter connectorInfoConverter,
                              final ConnectorContext connectorContext) {
    this.catalogName = catalogName;
    this.ctx = new AnnotationConfigApplicationContext();
    this.ctx.setEnvironment(new StandardEnvironment());
    this.ctx.getBeanFactory().registerSingleton("ConnectorContext", connectorContext);
    this.ctx.getBeanFactory().registerSingleton("ConnectorInfoConverter", connectorInfoConverter);
}
项目:spring4-understanding    文件:AnnotatedBeanDefinitionReader.java   
/**
 * 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();
}
项目:spring4-understanding    文件:ClassPathBeanDefinitionScanner.java   
/**
 * 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();
}
项目:spring4-understanding    文件:AsmCircularImportDetectionTests.java   
@Override
protected ConfigurationClassParser newParser() {
    return new ConfigurationClassParser(
            new CachingMetadataReaderFactory(),
            new FailFastProblemReporter(),
            new StandardEnvironment(),
            new DefaultResourceLoader(),
            new AnnotationBeanNameGenerator(),
            new DefaultListableBeanFactory());
}