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

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

@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {

    /**
     * Gets Logger After LoggingSystem configuration ready
     * @see LoggingApplicationListener
     */
    final Logger logger = LoggerFactory.getLogger(getClass());

    ConfigurableEnvironment environment = event.getEnvironment();

    boolean override = environment.getProperty(OVERRIDE_CONFIG_FULL_PROPERTY_NAME, boolean.class,
            DEFAULT_OVERRIDE_CONFIG_PROPERTY_VALUE);

    if (override) {

        SortedMap<String, Object> dubboProperties = filterDubboProperties(environment);

        ConfigUtils.getProperties().putAll(dubboProperties);

        if (logger.isInfoEnabled()) {
            logger.info("Dubbo Config was overridden by externalized configuration {}", dubboProperties);
        }
    } else {
        if (logger.isInfoEnabled()) {
            logger.info("Disable override Dubbo Config caused by property {} = {}", OVERRIDE_CONFIG_FULL_PROPERTY_NAME, override);
        }
    }

}
 
源代码2 项目: springCloud   文件: MyEnvironmentPostProcessor.java
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment,SpringApplication application) {
    //自定义配置文件
    String[] profiles = {
            "eureka.properties",
            "datasource.properties",
            "config.properties",
            "tx-lcn.properties",
            "feign.properties"
    };

    //循环添加
    for (String profile : profiles) {
        //从classpath路径下面查找文件
        Resource resource = new ClassPathResource(profile);
        //加载成PropertySource对象,并添加到Environment环境中
        environment.getPropertySources().addLast(loadProfiles(resource));
    }
}
 
源代码3 项目: Cleanstone   文件: SpringBootUrlReplacer.java
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
    ConfigurableEnvironment environment = applicationContext.getEnvironment();

    String springBootAdminServerUrl = environment.getProperty("web.client.url");
    if (environment.getProperty("web.admin.enabled", Boolean.class, false)) {
        springBootAdminServerUrl = "http://" + environment.getProperty("web.server.address") + ":" + environment.getProperty("web.server.port");
    }
    properties.put("spring.boot.admin.client.url", springBootAdminServerUrl);

    properties.put("spring.boot.admin.ui.public-url", environment.getProperty("web.admin.url"));
    properties.put("server.port", environment.getProperty("web.server.port"));
    properties.put("server.address", environment.getProperty("web.server.address"));

    environment.getPropertySources().addFirst(new PropertySource<>("spring-boot-admin-property-source") {
        @Override
        public Object getProperty(@NonNull String name) {
            if (properties.containsKey(name)) {
                return properties.get(name);
            }
            return null;
        }
    });
}
 
@Override
public String[] selectImports(AnnotationMetadata metadata) {
    String[] imports = super.selectImports(metadata);

    Environment env = getEnvironment();
    String grayEnabled = env.getProperty("gray.enabled");
    if (StringUtils.isEmpty(grayEnabled)) {
        if (ConfigurableEnvironment.class.isInstance(env)) {
            ConfigurableEnvironment environment = (ConfigurableEnvironment) env;
            MutablePropertySources m = environment.getPropertySources();
            Properties p = new Properties();
            p.put("gray.enabled", "true");
            m.addLast(new PropertiesPropertySource("defaultProperties", p));
        }
    }

    return imports;
}
 
@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 clientSecurityIsDisabledWhenEnablePropertyIsTrueAndCloudFoundryIsNotActive() {

	AutoConfiguredCloudSecurityEnvironmentPostProcessor environmentPostProcessor =
		spy(new AutoConfiguredCloudSecurityEnvironmentPostProcessor());

	doNothing().when(environmentPostProcessor).configureSecurityContext(any(ConfigurableEnvironment.class));

	ConfigurableEnvironment mockEnvironment = mock(ConfigurableEnvironment.class);

	when(mockEnvironment.containsProperty(eq("VCAP_APPLICATION"))).thenReturn(false);
	when(mockEnvironment.containsProperty(eq("VCAP_SERVICES"))).thenReturn(false);

	when(mockEnvironment.getProperty(eq(ClientSecurityAutoConfiguration.CLOUD_SECURITY_ENVIRONMENT_POST_PROCESSOR_ENABLED_PROPERTY),
		eq(Boolean.class), eq(true))).thenReturn(true);

	environmentPostProcessor.postProcessEnvironment(mockEnvironment, null);

	verify(mockEnvironment, times(1))
		.getProperty(eq(ClientSecurityAutoConfiguration.CLOUD_SECURITY_ENVIRONMENT_POST_PROCESSOR_ENABLED_PROPERTY),
			eq(Boolean.class), eq(true));

	verify(mockEnvironment, times(1)).containsProperty(eq("VCAP_APPLICATION"));
	verify(mockEnvironment, times(1)).containsProperty(eq("VCAP_SERVICES"));
	verify(environmentPostProcessor, never()).configureSecurityContext(eq(mockEnvironment));
}
 
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()]));
}
 
源代码8 项目: spring-javaformat   文件: SpringApplication.java
private void prepareContext(ConfigurableApplicationContext context,
		ConfigurableEnvironment environment, SpringApplicationRunListeners listeners,
		ApplicationArguments applicationArguments, Banner printedBanner) {
	context.setEnvironment(environment);
	postProcessApplicationContext(context);
	applyInitializers(context);
	listeners.contextPrepared(context);
	if (this.logStartupInfo) {
		logStartupInfo(context.getParent() == null);
		logStartupProfileInfo(context);
	}

	// Add boot specific singleton beans
	context.getBeanFactory().registerSingleton("springApplicationArguments",
			applicationArguments);
	if (printedBanner != null) {
		context.getBeanFactory().registerSingleton("springBootBanner", printedBanner);
	}

	// Load the sources
	Set<Object> sources = getAllSources();
	Assert.notEmpty(sources, "Sources must not be empty");
	load(context, sources.toArray(new Object[0]));
	listeners.contextLoaded(context);
}
 
protected LoggingProperties parseProperties(ConfigurableEnvironment environment) {
    LoggingProperties properties = Binder.get(environment)
            .bind(LoggingProperties.PREFIX, LoggingProperties.class)
            .orElseGet(LoggingProperties::new);

    if (isSet(environment, "trace")) {
        logger.info("debug mode, set default threshold to trace");
        properties.getDefaultSpec().setThreshold("trace");
    } else if (isSet(environment, "debug")) {
        logger.info("debug mode, set default threshold to debug");
        properties.getDefaultSpec().setThreshold("debug");
    } else {
        properties.getDefaultSpec().setThreshold("info");
    }

    return properties;
}
 
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {

    PropertySource<?> system = environment.getPropertySources()
        .get(SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME);

    Map<String, Object> prefixed = new LinkedHashMap<>();

    if (!hasOurPriceProperties(system)) {
        // Baeldung-internal code so this doesn't break other examples
        logger.warn("System environment variables [calculation_mode,gross_calculation_tax_rate] not detected, fallback to default value [calcuation_mode={},gross_calcuation_tax_rate={}]", CALCUATION_MODE_DEFAULT_VALUE,
            GROSS_CALCULATION_TAX_RATE_DEFAULT_VALUE);
        prefixed = names.stream()
            .collect(Collectors.toMap(this::rename, this::getDefaultValue));
        environment.getPropertySources()
            .addAfter(SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, new MapPropertySource("prefixer", prefixed));
        return;
    }

    prefixed = names.stream()
        .collect(Collectors.toMap(this::rename, system::getProperty));
    environment.getPropertySources()
        .addAfter(SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, new MapPropertySource("prefixer", prefixed));

}
 
源代码11 项目: cloudbreak   文件: IntegrationTestConfiguration.java
private Map<String, String> getAllKnownProperties(Environment env) {
    Map<String, String> rtn = new HashMap<>();
    if (env instanceof ConfigurableEnvironment) {
        for (PropertySource<?> propertySource : ((ConfigurableEnvironment) env).getPropertySources()) {
            if (propertySource instanceof EnumerablePropertySource) {
                LOGGER.info("processing property source ::: " + propertySource.getName());
                for (String key : ((EnumerablePropertySource) propertySource).getPropertyNames()) {
                    String value = propertySource.getProperty(key).toString();
                    LOGGER.debug("{} = {}", key, value);
                    if (!StringUtils.isEmpty(value) && !rtn.containsKey(key)) {
                        rtn.put(key, propertySource.getProperty(key).toString());
                    }
                }
            }
        }
    }
    return rtn;
}
 
源代码12 项目: tx-lcn   文件: H2DbProperties.java
public H2DbProperties(
        @Autowired(required = false) ConfigurableEnvironment environment,
        @Autowired(required = false) ServerProperties serverProperties) {
    String applicationName = "application";
    Integer port = 0;
    if (Objects.nonNull(environment)) {
        applicationName = environment.getProperty("spring.application.name");
    }
    if (Objects.nonNull(serverProperties)) {
        port = serverProperties.getPort();
    }
    this.filePath = System.getProperty("user.dir") +
            File.separator +
            ".txlcn" +
            File.separator +
            (StringUtils.hasText(applicationName) ? applicationName : "application") +
            "-" + port;
}
 
@Before
public void setup() throws Exception {
	this.client = new ReactorNettyWebSocketClient();

	this.server = new ReactorHttpServer();
	this.server.setHandler(createHttpHandler());
	this.server.afterPropertiesSet();
	this.server.start();

	// Set dynamically chosen port
	this.serverPort = this.server.getPort();

	if (this.client instanceof Lifecycle) {
		((Lifecycle) this.client).start();
	}

	this.gatewayContext = new SpringApplicationBuilder(GatewayConfig.class)
			.properties("ws.server.port:" + this.serverPort, "server.port=0",
					"spring.jmx.enabled=false")
			.run();

	ConfigurableEnvironment env = this.gatewayContext
			.getBean(ConfigurableEnvironment.class);
	this.gatewayPort = Integer.valueOf(env.getProperty("local.server.port"));
}
 
@Bean
public BeanDefinitionRegistryPostProcessor postProcessor(ConfigurableEnvironment environment) {
    return new BeanDefinitionRegistryPostProcessor() {
        @Override
        public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
            MutablePropertySources propertySources = environment.getPropertySources();
            Map<String, Object> source = new HashMap<>();
            source.put("enabled", "true");
            propertySources.addFirst(new MapPropertySource("for @ConditionalOnProperty", source));
        }

        @Override
        public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        }
    };
}
 
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
    String liquibaseProperty = getLiquibaseProperty();
    if (!environment.containsProperty(liquibaseProperty)) {
        LOGGER.warn("Liquibase has not been explicitly enabled or disabled. Overriding default from Spring Boot from `true` to `false`. "
            + "Flowable pulls in Liquibase, but does not use the Spring Boot configuration for it. "
            + "If you are using it you would need to set `{}` to `true` by yourself", liquibaseProperty);
        Map<String, Object> source = new HashMap<>();
        source.put(liquibaseProperty, false);
        environment.getPropertySources().addLast(new MapPropertySource("flowable-liquibase-override", source));
    }
}
 
/**
 * Propagates the given custom {@code Environment} to the underlying
 * {@link AnnotatedBeanDefinitionReader} and {@link ClassPathBeanDefinitionScanner}.
 */
@Override
public void setEnvironment(ConfigurableEnvironment environment) {
	super.setEnvironment(environment);
	this.reader.setEnvironment(environment);
	this.scanner.setEnvironment(environment);
}
 
@Override
public MapPropertySource locate(Environment environment) {
    if (environment instanceof ConfigurableEnvironment) {
        ConfigurableEnvironment env = (ConfigurableEnvironment) environment;
        String name = getApplicationName(environment, properties);
        String namespace = getApplicationNamespace(client, env, properties);
        return new ConfigMapPropertySource(client, name, namespace);
    }
    return null;
}
 
@Override
public void environmentPrepared(ConfigurableEnvironment env) {
    Properties props = new Properties();
    props.put(APOLLO_BOOTSTRAP_ENABLE_KEY, true);
    System.setProperty("spring.banner.location", "classpath:META-INF/banner.txt");
    env.getPropertySources().addFirst(new PropertiesPropertySource("apolloConfig", props));
    // 初始化环境
    this.initEnv(env);
    // 初始化appId
    this.initAppId(env);
    // 初始化架构提供的默认配置
    this.initInfraConfig(env);
}
 
/**
 * load log configuration in application.properties
 *
 * @param environment
 * @return
 */
private Map<String, String> loadApplicationEnvironment(ConfigurableEnvironment environment) {
    Map<String, String> context = new HashMap<String, String>();
    readLogConfiguration(LOG_PATH, environment.getProperty(LOG_PATH), context,
        Constants.LOGGING_PATH_DEFAULT);
    readLogConfiguration(OLD_LOG_PATH, environment.getProperty(OLD_LOG_PATH), context,
        context.get(LOG_PATH));
    readLogConfiguration(LOG_ENCODING_PROP_KEY, environment.getProperty(LOG_ENCODING_PROP_KEY),
        context);
    LogEnvUtils.keepCompatible(context, true);

    Set<String> configKeys = new HashSet<String>();
    Iterator<PropertySource<?>> propertySourceIterator = environment.getPropertySources()
        .iterator();
    while (propertySourceIterator.hasNext()) {
        PropertySource propertySource = propertySourceIterator.next();
        if (propertySource instanceof EnumerablePropertySource) {
            configKeys.addAll(Arrays.asList(((EnumerablePropertySource) propertySource)
                .getPropertyNames()));
        }
    }
    for (String key : configKeys) {
        if (LogEnvUtils.filterAllLogConfig(key)) {
            addToGlobalSystemProperties(key, environment.getProperty(key));
            readLogConfiguration(key, environment.getProperty(key), context);
        }
    }
    return context;
}
 
源代码20 项目: spring-analysis-note   文件: HttpServletBean.java
/**
 * Return the {@link Environment} associated with this servlet.
 * <p>If none specified, a default environment will be initialized via
 * {@link #createEnvironment()}.
 */
@Override
public ConfigurableEnvironment getEnvironment() {
	if (this.environment == null) {
		this.environment = createEnvironment();
	}
	return this.environment;
}
 
@Override
public void contextLoaded(ConfigurableApplicationContext context) {
    // 从 ConfigurableApplicationContext 获取 ConfigurableEnvironment
    ConfigurableEnvironment environment = context.getEnvironment();
    MutablePropertySources propertySources = environment.getPropertySources();
    // 通过名称获取名为 "systemProperties" 的 PropertySource(实现使用常量)
    PropertySource propertySource = propertySources.get(StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME);
    // 将 "systemProperties" 的 PropertySource 添加在 "contextPrepared" 之前(由 contextPrepared 方法添加),提高优先级
    propertySources.addBefore("contextPrepared", propertySource);
}
 
private void disableEndpoint(final ConfigurableListableBeanFactory beanFactory) {
    final ConfigurableEnvironment env = beanFactory.getBean(ConfigurableEnvironment.class);
    final MutablePropertySources propertySources = env.getPropertySources();
    propertySources.addFirst(
            new MapPropertySource(endpoint + "PropertySource", singletonMap("endpoints." + endpoint + ".enabled", false))
    );
}
 
@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
	
	ConfigurableEnvironment environment = event.getEnvironment();
	
	for(Iterator<PropertySource<?>> it = environment.getPropertySources().iterator();it.hasNext();) {
		PropertySource<?> propertySource = it.next();
		getPropertiesFromSource(propertySource);
	}
	
	logger.info("2 Enviroment准备完毕,  EnvironmentPreparedEventApplicationListener...");
}
 
@Bean
public MultipleJGitEnvironmentRepositoryFactory gitEnvironmentRepositoryFactory(
		ConfigurableEnvironment environment, ConfigServerProperties server,
		Optional<ConfigurableHttpConnectionFactory> jgitHttpConnectionFactory,
		Optional<TransportConfigCallback> customTransportConfigCallback,
		Optional<GoogleCloudSourceSupport> googleCloudSourceSupport) {
	final TransportConfigCallbackFactory transportConfigCallbackFactory = new TransportConfigCallbackFactory(
			customTransportConfigCallback.orElse(null),
			googleCloudSourceSupport.orElse(null));
	return new MultipleJGitEnvironmentRepositoryFactory(environment, server,
			jgitHttpConnectionFactory, transportConfigCallbackFactory);
}
 
@Override
public String[] selectImports(AnnotationMetadata metadata) {
	String[] imports = super.selectImports(metadata);

	AnnotationAttributes attributes = AnnotationAttributes.fromMap(
			metadata.getAnnotationAttributes(getAnnotationClass().getName(), true));

	boolean autoRegister = attributes.getBoolean("autoRegister");

	if (autoRegister) {
		List<String> importsList = new ArrayList<>(Arrays.asList(imports));
		importsList.add(
				"org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationConfiguration");
		imports = importsList.toArray(new String[0]);
	}
	else {
		Environment env = getEnvironment();
		if (ConfigurableEnvironment.class.isInstance(env)) {
			ConfigurableEnvironment configEnv = (ConfigurableEnvironment) env;
			LinkedHashMap<String, Object> map = new LinkedHashMap<>();
			map.put("spring.cloud.service-registry.auto-registration.enabled", false);
			MapPropertySource propertySource = new MapPropertySource(
					"springCloudDiscoveryClient", map);
			configEnv.getPropertySources().addLast(propertySource);
		}

	}

	return imports;
}
 
/**
 * {@inheritDoc}
 * <p>Replace {@code Servlet}-related property sources.
 */
@Override
protected void initPropertySources() {
	ConfigurableEnvironment env = getEnvironment();
	if (env instanceof ConfigurableWebEnvironment) {
		((ConfigurableWebEnvironment) env).initPropertySources(this.servletContext, this.servletConfig);
	}
}
 
源代码27 项目: wallride   文件: WallRideInitializer.java
public static ConfigurableEnvironment createEnvironment(ApplicationStartingEvent event) {
	StandardEnvironment environment = new StandardEnvironment();

	String home = environment.getProperty(WallRideProperties.HOME_PROPERTY);
	if (!StringUtils.hasText(home)) {
		//try to get config-File with wallride.home parameter under webroot
		String configFileHome = getConfigFileHome(event);
		if (configFileHome!=null) {
			home = configFileHome;
		} else {
			throw new IllegalStateException(WallRideProperties.HOME_PROPERTY + " is empty");
		}
	}
	if (!home.endsWith("/")) {
		home = home + "/";
	}

	String config = home + WallRideProperties.DEFAULT_CONFIG_PATH_NAME;
	String media = home + WallRideProperties.DEFAULT_MEDIA_PATH_NAME;

	System.setProperty(WallRideProperties.CONFIG_LOCATION_PROPERTY, config);
	System.setProperty(WallRideProperties.MEDIA_LOCATION_PROPERTY, media);

	event.getSpringApplication().getListeners().stream()
			.filter(listener -> listener.getClass().isAssignableFrom(ConfigFileApplicationListener.class))
			.map(listener -> (ConfigFileApplicationListener) listener)
			.forEach(listener -> listener.setSearchLocations(DEFAULT_CONFIG_SEARCH_LOCATIONS + "," + config));

	return environment;
}
 
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
    MutablePropertySources propertySources = environment.getPropertySources();
    Map<String, Object> defaultProperties = createDefaultProperties(environment);
    if (!CollectionUtils.isEmpty(defaultProperties)) {
        addOrReplace(propertySources, defaultProperties);
    }
}
 
源代码29 项目: netstrap   文件: NetstrapBootApplication.java
/**
 * 装配SpringContext
 * 设置环境,初始化调用,设置监听器
 */
private void prepareContext(ConfigurableApplicationContext context, ConfigurableEnvironment environment) {
    context.setEnvironment(environment);
    applyInitializer(context);
    for (ApplicationListener listener : listeners) {
        context.addApplicationListener(listener);
    }
}
 
源代码30 项目: spring4-understanding   文件: FrameworkServlet.java
protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac) {
	if (ObjectUtils.identityToString(wac).equals(wac.getId())) {
		// The application context id is still set to its original default value
		// -> assign a more useful id based on available information
		if (this.contextId != null) {
			wac.setId(this.contextId);
		}
		else {
			// Generate default id...
			wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +
					ObjectUtils.getDisplayString(getServletContext().getContextPath()) + "/" + getServletName());
		}
	}

	wac.setServletContext(getServletContext());
	wac.setServletConfig(getServletConfig());
	wac.setNamespace(getNamespace());
	wac.addApplicationListener(new SourceFilteringListener(wac, new ContextRefreshListener()));

	// The wac environment's #initPropertySources will be called in any case when the context
	// is refreshed; do it eagerly here to ensure servlet property sources are in place for
	// use in any post-processing or initialization that occurs below prior to #refresh
	ConfigurableEnvironment env = wac.getEnvironment();
	if (env instanceof ConfigurableWebEnvironment) {
		((ConfigurableWebEnvironment) env).initPropertySources(getServletContext(), getServletConfig());
	}

	postProcessWebApplicationContext(wac);
	applyInitializers(wac);
	wac.refresh();
}