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

The following examples show how to use org.springframework.core.env.ConfigurableEnvironment#getProperty() . 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: OverrideDubboConfigApplicationListener.java    From dubbo-spring-boot-project with Apache License 2.0 21 votes vote down vote up
@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);
        }
    }

}
 
Example 2
Source File: FunctionDeployerConfiguration.java    From spring-cloud-function with Apache License 2.0 7 votes vote down vote up
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
String functionName = environment.containsProperty("function.name") ? environment.getProperty("function.name") : null;
	String functionLocation = environment.containsProperty("function.location") ? environment.getProperty("function.location") : null;
	if (StringUtils.hasText(functionName) || StringUtils.hasText(functionLocation)) {
		MutablePropertySources propertySources = environment.getPropertySources();
		propertySources.forEach(ps -> {
			if (ps instanceof PropertiesPropertySource) {
				((MapPropertySource) ps).getSource().put(FunctionProperties.PREFIX + ".definition", functionName);
				((MapPropertySource) ps).getSource().put(FunctionProperties.PREFIX + ".location", functionLocation);
			}
		});
	}
}
 
Example 3
Source File: MicrometerSpringApplicationRunListener.java    From summerframework with Apache License 2.0 7 votes vote down vote up
@Override
public void environmentPrepared(ConfigurableEnvironment environment) {
    new TransactionManagerCustomizer().apply(environment);
    if (environment.getProperty(METRICS_INFLUX_ENABLED) == null) {
        logger.info("{} not set. Default enable", METRICS_INFLUX_ENABLED);
        Properties props = createProperties(environment);
        logger.info("summerframeworkMicrometer = {}", props);
        environment.getPropertySources().addLast(new PropertiesPropertySource("summerframeworkMicrometer", props));
    }
}
 
Example 4
Source File: SpringbootApplication.java    From molicode with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {

        SpringApplicationBuilder builder = new SpringApplicationBuilder(SpringbootApplication.class);
        ConfigurableApplicationContext configurableApplicationContext = builder.headless(false).web(WebApplicationType.SERVLET).run(args);
        ConfigurableEnvironment configurableEnvironment = configurableApplicationContext.getEnvironment();
        final String port = configurableEnvironment.getProperty("server.port", "8086");
        final String windowName = configurableEnvironment.getProperty("browser.windowName", BrowserWindowEnum.SWING.getCode());

        final String url = "http://127.0.0.1:" + port + "/index.html?t=" + System.currentTimeMillis();
        LogHelper.DEFAULT.info("server started success! windowName={}, url is: {}", windowName, url);

        //headless状态下,无开启窗口
        if (!Objects.equals(windowName, BrowserWindowEnum.HEADLESS.getCode())) {
            GuiWindowFactory.getInstance().createWindow(windowName).initAndOpen(url);

        }
    }
 
Example 5
Source File: DefinitionPropertySourceFactory.java    From seppb with MIT License 6 votes vote down vote up
/**
 * 从外部获取配置文件,并对加密后的数据库用户名和密码做解密
 *
 * @param environment
 * @param application
 */
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
    String configPath = environment.getProperty("path");
    if (Env.getCurrentEnv() == LOCAL) {
        eagerLoad(environment);
        return;
    }
    File file = new File(defaultIfBlank(configPath, "/opt/sqcs_backend/spring.properties"));
    log.info("configPath:{}", configPath);
    try (InputStream input = new FileInputStream(file)) {
        Properties properties = buildDecryptProperties(input);
        PropertiesPropertySource propertySource = new PropertiesPropertySource("spring", properties);
        environment.getPropertySources().addLast(propertySource);
    } catch (Exception e) {
        throw new SeppServerException("配置文件读取错误", e);
    }
}
 
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: MultRegisterCenterServerMgmtConfig.java    From Moss with Apache License 2.0 6 votes vote down vote up
private String getProperty(String property, ConfigurableEnvironment env) {
    return env.containsProperty(property) ? env.getProperty(property) : "";
}
 
Example 8
Source File: SofaTracerConfigurationListener.java    From sofa-tracer with Apache License 2.0 6 votes vote down vote up
@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
    ConfigurableEnvironment environment = event.getEnvironment();

    if (SOFABootEnvUtils.isSpringCloudBootstrapEnvironment(environment)) {
        return;
    }

    // set loggingPath
    String loggingPath = environment.getProperty("logging.path");
    if (StringUtils.isNotBlank(loggingPath)) {
        System.setProperty("logging.path", loggingPath);
    }

    // check spring.application.name
    String applicationName = environment
        .getProperty(SofaTracerConfiguration.TRACER_APPNAME_KEY);
    Assert.isTrue(!StringUtils.isBlank(applicationName),
        SofaTracerConfiguration.TRACER_APPNAME_KEY + " must be configured!");
    SofaTracerConfiguration.setProperty(SofaTracerConfiguration.TRACER_APPNAME_KEY,
        applicationName);

    SofaTracerProperties tempTarget = new SofaTracerProperties();
    PropertiesConfigurationFactory<SofaTracerProperties> binder = new PropertiesConfigurationFactory<SofaTracerProperties>(
        tempTarget);
    ConfigurationProperties configurationPropertiesAnnotation = this
        .getConfigurationPropertiesAnnotation(tempTarget);
    if (configurationPropertiesAnnotation != null
        && StringUtils.isNotBlank(configurationPropertiesAnnotation.prefix())) {
        //consider compatible Spring Boot 1.5.X and 2.x
        binder.setIgnoreInvalidFields(configurationPropertiesAnnotation.ignoreInvalidFields());
        binder.setIgnoreUnknownFields(configurationPropertiesAnnotation.ignoreUnknownFields());
        binder.setTargetName(configurationPropertiesAnnotation.prefix());
    } else {
        binder.setTargetName(SofaTracerProperties.SOFA_TRACER_CONFIGURATION_PREFIX);
    }
    binder.setConversionService(new DefaultConversionService());
    binder.setPropertySources(environment.getPropertySources());
    try {
        binder.bindPropertiesToTarget();
    } catch (BindException ex) {
        throw new IllegalStateException("Cannot bind to SofaTracerProperties", ex);
    }

    //properties convert to tracer
    SofaTracerConfiguration.setProperty(
        SofaTracerConfiguration.DISABLE_MIDDLEWARE_DIGEST_LOG_KEY,
        tempTarget.getDisableDigestLog());
    SofaTracerConfiguration.setProperty(SofaTracerConfiguration.DISABLE_DIGEST_LOG_KEY,
        tempTarget.getDisableConfiguration());
    SofaTracerConfiguration.setProperty(SofaTracerConfiguration.TRACER_GLOBAL_ROLLING_KEY,
        tempTarget.getTracerGlobalRollingPolicy());
    SofaTracerConfiguration.setProperty(SofaTracerConfiguration.TRACER_GLOBAL_LOG_RESERVE_DAY,
        tempTarget.getTracerGlobalLogReserveDay());
    //stat log interval
    SofaTracerConfiguration.setProperty(SofaTracerConfiguration.STAT_LOG_INTERVAL,
        tempTarget.getStatLogInterval());
    //baggage length
    SofaTracerConfiguration.setProperty(
        SofaTracerConfiguration.TRACER_PENETRATE_ATTRIBUTE_MAX_LENGTH,
        tempTarget.getBaggageMaxLength());
    SofaTracerConfiguration.setProperty(
        SofaTracerConfiguration.TRACER_SYSTEM_PENETRATE_ATTRIBUTE_MAX_LENGTH,
        tempTarget.getBaggageMaxLength());

    //sampler config
    if (tempTarget.getSamplerName() != null) {
        SofaTracerConfiguration.setProperty(SofaTracerConfiguration.SAMPLER_STRATEGY_NAME_KEY,
            tempTarget.getSamplerName());
    }
    if (StringUtils.isNotBlank(tempTarget.getSamplerCustomRuleClassName())) {
        SofaTracerConfiguration.setProperty(
            SofaTracerConfiguration.SAMPLER_STRATEGY_CUSTOM_RULE_CLASS_NAME,
            tempTarget.getSamplerCustomRuleClassName());
    }
    SofaTracerConfiguration.setProperty(
        SofaTracerConfiguration.SAMPLER_STRATEGY_PERCENTAGE_KEY,
        String.valueOf(tempTarget.getSamplerPercentage()));

    SofaTracerConfiguration.setProperty(SofaTracerConfiguration.JSON_FORMAT_OUTPUT,
        String.valueOf(tempTarget.isJsonOutput()));
}
 
Example 9
Source File: TraceReactorAutoConfiguration.java    From spring-cloud-sleuth with Apache License 2.0 6 votes vote down vote up
static void setupHooks(ConfigurableApplicationContext springContext) {
	ConfigurableEnvironment environment = springContext.getEnvironment();
	boolean decorateOnEach = environment.getProperty(
			"spring.sleuth.reactor.decorate-on-each", Boolean.class, true);
	if (decorateOnEach) {
		if (log.isTraceEnabled()) {
			log.trace("Decorating onEach operator instrumentation");
		}
		Hooks.onEachOperator(SLEUTH_TRACE_REACTOR_KEY,
				scopePassingSpanOperator(springContext));
	}
	else {
		if (log.isTraceEnabled()) {
			log.trace("Decorating onLast operator instrumentation");
		}
		Hooks.onLastOperator(SLEUTH_TRACE_REACTOR_KEY,
				scopePassingSpanOperator(springContext));
	}
	Schedulers.setExecutorServiceDecorator(
			TraceReactorAutoConfiguration.SLEUTH_REACTOR_EXECUTOR_SERVICE_KEY,
			(scheduler,
					scheduledExecutorService) -> new TraceableScheduledExecutorService(
							springContext, scheduledExecutorService));
}
 
Example 10
Source File: DefaultParameterStorePropertySourceConfigurationStrategy.java    From spring-boot-parameter-store-integration with MIT License 6 votes vote down vote up
private String getCustomEndpoint(ConfigurableEnvironment environment)
{
    return environment.getProperty(ParameterStorePropertySourceConfigurationProperties.SSM_CLIENT_CUSTOM_ENDPOINT);
}
 
Example 11
Source File: SpacedLogbackSystem.java    From spring-cloud-formula with Apache License 2.0 6 votes vote down vote up
protected boolean isSet(ConfigurableEnvironment environment, String property) {
    String value = environment.getProperty(property);
    return (value != null && !value.equals("false"));
}
 
Example 12
Source File: RpcDefinitionPostProcessor.java    From joyrpc with Apache License 2.0 6 votes vote down vote up
/**
 * 构造方法
 */
public RpcDefinitionPostProcessor(final ApplicationContext applicationContext,
                                  final ConfigurableEnvironment environment,
                                  final ResourceLoader resourceLoader) {
    this.applicationContext = applicationContext;
    this.environment = environment;
    this.resourceLoader = resourceLoader;
    this.counter = Counter.getOrCreate(applicationContext);
    this.rpcProperties = Binder.get(environment).bind(RPC_PREFIX, RpcProperties.class).orElseGet(RpcProperties::new);
    //值引用前缀
    this.refPrefix = environment.getProperty(REF_PREFIX_KEY, REF_PREFIX);
    //添加消费者
    if (rpcProperties.getConsumers() != null) {
        rpcProperties.getConsumers().forEach(c -> addConfig(c, CONSUMER_PREFIX, consumerNameCounters, consumers));
    }
    //添加消费组
    if (rpcProperties.getGroups() != null) {
        rpcProperties.getGroups().forEach(c -> addConfig(c, CONSUMER_PREFIX, consumerNameCounters, groups));
    }
    //添加服务提供者
    if (rpcProperties.getProviders() != null) {
        rpcProperties.getProviders().forEach(c -> addConfig(c, PROVIDER_PREFIX, providerNameCounters, providers));
    }
}
 
Example 13
Source File: ApolloApplicationContextInitializer.java    From apollo with Apache License 2.0 5 votes vote down vote up
private void fillSystemPropertyFromEnvironment(ConfigurableEnvironment environment, String propertyName) {
  if (System.getProperty(propertyName) != null) {
    return;
  }

  String propertyValue = environment.getProperty(propertyName);

  if (Strings.isNullOrEmpty(propertyValue)) {
    return;
  }

  System.setProperty(propertyName, propertyValue);
}
 
Example 14
Source File: ParameterStorePropertySourceEnvironmentPostProcessor.java    From spring-boot-parameter-store-integration with MIT License 5 votes vote down vote up
private boolean isParameterStorePropertySourceEnabled(ConfigurableEnvironment environment)
{
    String[] userDefinedEnabledProfiles = environment.getProperty(ParameterStorePropertySourceConfigurationProperties.ACCEPTED_PROFILES,
                                                                  String[].class);
    return environment.getProperty(ParameterStorePropertySourceConfigurationProperties.ENABLED,
                                   Boolean.class,
                                   Boolean.FALSE)
            || environment.acceptsProfiles(ParameterStorePropertySourceConfigurationProperties.ENABLED_PROFILE)
            || (!ObjectUtils.isEmpty(userDefinedEnabledProfiles)
                    && environment.acceptsProfiles(userDefinedEnabledProfiles));
}
 
Example 15
Source File: ApolloSpringApplicationRunListener.java    From summerframework with Apache License 2.0 5 votes vote down vote up
private void initAppId(ConfigurableEnvironment env) {
    String applicationName = env.getProperty(SPRINGBOOT_APPLICATION_NAME);
    String apolloAppId = env.getProperty(APOLLO_APP_ID_KEY);
    if (StringUtils.isEmpty(apolloAppId)) {
        if (!StringUtils.isEmpty(applicationName)) {
            System.setProperty(APOLLO_APP_ID_KEY, applicationName);
        } else {
            throw new IllegalArgumentException(
                "Config center must config app.id in " + DefaultApplicationProvider.APP_PROPERTIES_CLASSPATH);
        }
    } else {
        System.setProperty(APOLLO_APP_ID_KEY, apolloAppId);
    }
}
 
Example 16
Source File: SpringApplication.java    From spring-javaformat with Apache License 2.0 5 votes vote down vote up
private void configureIgnoreBeanInfo(ConfigurableEnvironment environment) {
	if (System.getProperty(
			CachedIntrospectionResults.IGNORE_BEANINFO_PROPERTY_NAME) == null) {
		Boolean ignore = environment.getProperty("spring.beaninfo.ignore",
				Boolean.class, Boolean.TRUE);
		System.setProperty(CachedIntrospectionResults.IGNORE_BEANINFO_PROPERTY_NAME,
				ignore.toString());
	}
}
 
Example 17
Source File: MissingSpringCloudRegistryConfigPropertyCondition.java    From spring-cloud-alibaba with Apache License 2.0 5 votes vote down vote up
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context,
		AnnotatedTypeMetadata metadata) {
	ConfigurableEnvironment environment = (ConfigurableEnvironment) context
			.getEnvironment();

	String protocol = environment.getProperty("dubbo.registry.protocol");

	if (PROTOCOL.equals(protocol)) {
		return ConditionOutcome.noMatch(
				"'spring-cloud' protocol was found from 'dubbo.registry.protocol'");
	}

	String address = environment.getProperty("dubbo.registry.address");

	if (StringUtils.startsWithIgnoreCase(address, PROTOCOL)) {
		return ConditionOutcome.noMatch(
				"'spring-cloud' protocol was found from 'dubbo.registry.address'");
	}

	Map<String, Object> properties = getSubProperties(
			environment.getPropertySources(), "dubbo.registries.");

	boolean found = properties.entrySet().stream().anyMatch(entry -> {
		String key = entry.getKey();
		String value = String.valueOf(entry.getValue());
		return (key.endsWith(".address") && value.startsWith(PROTOCOL))
				|| (key.endsWith(".protocol") && PROTOCOL.equals(value));

	});

	return found
			? ConditionOutcome.noMatch(
					"'spring-cloud' protocol was found in 'dubbo.registries.*'")
			: ConditionOutcome.match();
}
 
Example 18
Source File: BannerListener.java    From mPass with Apache License 2.0 5 votes vote down vote up
@Override
public void environmentPrepared(ConfigurableEnvironment environment) {
    if(springApplication.getWebApplicationType() == WebApplicationType.NONE){
        return;
    }

    if (executed.compareAndSet(false, true)) {
        String bannerConfig = environment.getProperty(SpringApplication.BANNER_LOCATION_PROPERTY);
        if (StringUtils.isEmpty(bannerConfig)) {
            URL url = BannerListener.class.getResource(BANNER_PATH);
            springApplication.setBanner(new ResourceBanner(new UrlResource(url)));
        }
    }
}
 
Example 19
Source File: LogbackListener.java    From mPaaS with Apache License 2.0 5 votes vote down vote up
@Override
public void environmentPrepared(ConfigurableEnvironment environment) {
    if (executed.compareAndSet(false, true)) {
        String logConfig = environment.getProperty(LoggingApplicationListener.CONFIG_PROPERTY);
        if (StringUtils.isEmpty(logConfig)) {
            URL url = LogbackListener.class.getResource(LOGBACK_CFG_NAME);
            String filePath = url.getPath();
            if (filePath.indexOf(ResourceUtils.JAR_FILE_EXTENSION) > -1) {
                filePath = ResourceUtils.JAR_URL_PREFIX + filePath;
            }
            System.setProperty(LoggingApplicationListener.CONFIG_PROPERTY, filePath);
        }
    }
}
 
Example 20
Source File: SpringBootPlusAdminApplication.java    From spring-boot-plus with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {
    ConfigurableApplicationContext context = SpringApplication.run(SpringBootPlusAdminApplication.class, args);
    ConfigurableEnvironment environment = context.getEnvironment();
    String serverPort = environment.getProperty("server.port");
    log.info("SpringBootAdmin: http://localhost:" + serverPort);
}