Java Code Examples for org.springframework.core.env.ConfigurableEnvironment#setActiveProfiles()

The following examples show how to use org.springframework.core.env.ConfigurableEnvironment#setActiveProfiles() . 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: PropertySourceBootstrapConfiguration.java    From spring-cloud-commons with Apache License 2.0 6 votes vote down vote up
private void handleIncludedProfiles(ConfigurableEnvironment environment) {
	Set<String> includeProfiles = new TreeSet<>();
	for (PropertySource<?> propertySource : environment.getPropertySources()) {
		addIncludedProfilesTo(includeProfiles, propertySource);
	}
	List<String> activeProfiles = new ArrayList<>();
	Collections.addAll(activeProfiles, environment.getActiveProfiles());

	// If it's already accepted we assume the order was set intentionally
	includeProfiles.removeAll(activeProfiles);
	if (includeProfiles.isEmpty()) {
		return;
	}
	// Prepend each added profile (last wins in a property key clash)
	for (String profile : includeProfiles) {
		activeProfiles.add(0, profile);
	}
	environment.setActiveProfiles(
			activeProfiles.toArray(new String[activeProfiles.size()]));
}
 
Example 2
Source File: NestedBeansElementTests.java    From spring-analysis-note 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 3
Source File: SpringBootLambdaContainerHandler.java    From aws-serverless-java-container with Apache License 2.0 6 votes vote down vote up
@Override
public void initialize()
        throws ContainerInitializationException {
    Timer.start("SPRINGBOOT_COLD_START");

    SpringApplication app = new SpringApplication(
            springBootInitializer,
            ServerlessServletEmbeddedServerFactory.class,
            SpringBootServletConfigurationSupport.class
    );
    if (springProfiles != null && springProfiles.length > 0) {
        ConfigurableEnvironment springEnv = new StandardEnvironment();
        springEnv.setActiveProfiles(springProfiles);
        app.setEnvironment(springEnv);
    }
    ConfigurableApplicationContext applicationContext = app.run();

    ((ConfigurableWebApplicationContext)applicationContext).setServletContext(getServletContext());
    AwsServletRegistration reg = (AwsServletRegistration)getServletContext().getServletRegistration(DISPATCHER_SERVLET_REGISTRATION_NAME);
    if (reg != null) {
        reg.setLoadOnStartup(1);
    }
    super.initialize();
    initialized = true;
    Timer.stop("SPRINGBOOT_COLD_START");
}
 
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: 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 6
Source File: EnviromentDiscovery.java    From gazpachoquest with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void initialize(ConfigurableApplicationContext ctx) {
    ConfigurableEnvironment environment = ctx.getEnvironment();
    String activeProfiles[] = environment.getActiveProfiles();

    if (activeProfiles.length == 0) {
        environment.setActiveProfiles("test,db_hsql");
    }

    logger.info("Application running using profiles: {}", Arrays.toString(environment.getActiveProfiles()));

    String instanceInfoString = environment.getProperty(GAZPACHO_APP_KEY);

    String dbEngine = null;
    for (String profile : activeProfiles) {
        if (profile.startsWith("db_")) {
            dbEngine = profile;
            break;
        }
    }
    try {
        environment.getPropertySources().addLast(
                new ResourcePropertySource(String.format("classpath:/database/%s.properties", dbEngine)));
    } catch (IOException e) {
        throw new IllegalStateException(dbEngine + ".properties not found in classpath", e);
    }

    PropertySourcesPlaceholderConfigurer propertyHolder = new PropertySourcesPlaceholderConfigurer();

    Map<String, String> environmentProperties = parseInstanceInfo(instanceInfoString);
    if (!environmentProperties.isEmpty()) {
        logger.info("Overriding default properties with {}", instanceInfoString);
        Properties properties = new Properties();
        for (String key : environmentProperties.keySet()) {
            String value = environmentProperties.get(key);
            properties.put(key, value);
        }
        environment.getPropertySources().addLast(new PropertiesPropertySource("properties", properties));

        propertyHolder.setEnvironment(environment);
        // ctx.addBeanFactoryPostProcessor(propertyHolder);
        // ctx.refresh();
    }
}
 
Example 7
Source File: WorkerContextInitializer.java    From cloud-espm-cloud-native with Apache License 2.0 5 votes vote down vote up
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
	ConfigurableEnvironment applicationEnvironment = applicationContext.getEnvironment();
	Cloud cloud = getCloud();
	if (cloud != null) {
		applicationEnvironment.setActiveProfiles("cloud");

	} else {
		applicationEnvironment.setActiveProfiles("local");
	}

}
 
Example 8
Source File: ProfileInitializer.java    From AppStash with Apache License 2.0 5 votes vote down vote up
@Override
public void initialize(ConfigurableWebApplicationContext configurableWebApplicationContext) {
    ConfigurableEnvironment environment = configurableWebApplicationContext.getEnvironment();
    if (environment.getSystemEnvironment().containsKey("MONGODB_PORT_27017_TCP_ADDR") &&
            environment.getSystemEnvironment().containsKey("MONGODB_PORT_27017_TCP_PORT")) {
        environment.setActiveProfiles("docker");
    }
    if (!hasActiveProfile(environment)) {
        environment.setActiveProfiles("production");
    }
    LOGGER.info("Active profiles are {}", StringUtils.join(environment.getActiveProfiles(), ","));
}
 
Example 9
Source File: WebAnnoApplicationContextInitializer.java    From webanno with Apache License 2.0 5 votes vote down vote up
@Override
public void initialize(ConfigurableApplicationContext aApplicationContext)
{
    ConfigurableEnvironment aEnvironment = aApplicationContext.getEnvironment();

    File settings = SettingsUtil.getSettingsFile();
    
    // If settings were found, add them to the environment
    if (settings != null) {
        log.info("Settings: " + settings);
        try {
            aEnvironment.getPropertySources().addFirst(
                    new ResourcePropertySource(new FileSystemResource(settings)));
        }
        catch (IOException e) {
            throw new IllegalStateException(e);
        }
    }

    // Activate bean profile depending on authentication mode
    if (AUTH_MODE_PREAUTH.equals(aEnvironment.getProperty(SettingsUtil.CFG_AUTH_MODE))) {
        aEnvironment.setActiveProfiles(PROFILE_PREAUTH);
        log.info("Authentication: pre-auth");
    }
    else {
        aEnvironment.setActiveProfiles(PROFILE_DATABASE);
        log.info("Authentication: database");
    }
}
 
Example 10
Source File: SpringProfilesWithXMLIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void testSpringProfilesForDevEnvironment() {
    classPathXmlApplicationContext = new ClassPathXmlApplicationContext("classpath:springProfiles-config.xml");
    final ConfigurableEnvironment configurableEnvironment = classPathXmlApplicationContext.getEnvironment();
    configurableEnvironment.setActiveProfiles("dev");
    classPathXmlApplicationContext.refresh();
    final DatasourceConfig datasourceConfig = classPathXmlApplicationContext.getBean("devDatasourceConfig", DatasourceConfig.class);

    Assert.assertTrue(datasourceConfig instanceof DevDatasourceConfig);
}
 
Example 11
Source File: ClassPathScanningCandidateComponentProviderTests.java    From spring4-understanding with Apache License 2.0 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 12
Source File: ClassPathScanningCandidateComponentProviderTests.java    From spring-analysis-note 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 13
Source File: SpringProfilesWithXMLIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void testSpringProfilesForProdEnvironment() {
    classPathXmlApplicationContext = new ClassPathXmlApplicationContext("classpath:springProfiles-config.xml");
    final ConfigurableEnvironment configurableEnvironment = classPathXmlApplicationContext.getEnvironment();
    configurableEnvironment.setActiveProfiles("production");
    classPathXmlApplicationContext.refresh();
    final DatasourceConfig datasourceConfig = classPathXmlApplicationContext.getBean("productionDatasourceConfig", DatasourceConfig.class);

    Assert.assertTrue(datasourceConfig instanceof ProductionDatasourceConfig);
}
 
Example 14
Source File: TaxApplicationContextInitializer.java    From cloud-espm-cloud-native with Apache License 2.0 5 votes vote down vote up
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
	ConfigurableEnvironment applicationEnvironment = applicationContext.getEnvironment();
	Cloud cloud = getCloud();
	if (cloud != null) {
		logger.info("**********Initializing the application context for cloud env**********");
		applicationEnvironment.setActiveProfiles("cloud");

	} else {
		logger.info("**********Initializing the application context for local env**********");
		applicationEnvironment.setActiveProfiles("local");
	}

}
 
Example 15
Source File: InceptionApplicationContextInitializer.java    From inception with Apache License 2.0 5 votes vote down vote up
@Override
public void initialize(ConfigurableApplicationContext aApplicationContext)
{
    LoggingFilter.setLoggingUsername("SYSTEM");
            
    ConfigurableEnvironment aEnvironment = aApplicationContext.getEnvironment();

    File settings = SettingsUtil.getSettingsFile();
    
    // If settings were found, add them to the environment
    if (settings != null) {
        log.info("Settings: " + settings);
        try {
            aEnvironment.getPropertySources().addFirst(
                    new ResourcePropertySource(new FileSystemResource(settings)));
        }
        catch (IOException e) {
            throw new IllegalStateException(e);
        }
    }

    // Activate bean profile depending on authentication mode
    if (AUTH_MODE_PREAUTH.equals(aEnvironment.getProperty(SettingsUtil.CFG_AUTH_MODE))) {
        aEnvironment.setActiveProfiles(PROFILE_PREAUTH);
        log.info("Authentication: pre-auth");
    }
    else {
        aEnvironment.setActiveProfiles(PROFILE_DATABASE);
        log.info("Authentication: database");
    }
}
 
Example 16
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 17
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 18
Source File: SpringBootstrap.java    From sbp with Apache License 2.0 5 votes vote down vote up
@Override
protected void configurePropertySources(ConfigurableEnvironment environment,
                                        String[] args) {
    super.configurePropertySources(environment, args);
    String[] profiles = ((SpringBootPluginManager)
            plugin.getWrapper().getPluginManager()).getProfiles();
    if (!ArrayUtils.isEmpty(profiles)) environment.setActiveProfiles(profiles);
    environment.getPropertySources().addLast(new ExcludeConfigurations());
}
 
Example 19
Source File: ClassPathScanningCandidateComponentProviderTests.java    From spring-analysis-note 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 20
Source File: SpringApplication.java    From spring-javaformat with Apache License 2.0 3 votes vote down vote up
/**
 * Configure which profiles are active (or active by default) for this application
 * environment. Additional profiles may be activated during configuration file
 * processing via the {@code spring.profiles.active} property.
 * @param environment this application's environment
 * @param args arguments passed to the {@code run} method
 * @see #configureEnvironment(ConfigurableEnvironment, String[])
 * @see org.springframework.boot.context.config.ConfigFileApplicationListener
 */
protected void configureProfiles(ConfigurableEnvironment environment, String[] args) {
	environment.getActiveProfiles(); // ensure they are initialized
	// But these ones should go first (last wins in a property key clash)
	Set<String> profiles = new LinkedHashSet<>(this.additionalProfiles);
	profiles.addAll(Arrays.asList(environment.getActiveProfiles()));
	environment.setActiveProfiles(StringUtils.toStringArray(profiles));
}