org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent#getEnvironment ( )源码实例Demo

下面列出了org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent#getEnvironment ( ) 实例代码,或者点击链接到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);
        }
    }

}
 
@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()));
}
 
源代码3 项目: Kafdrop   文件: KafDrop.java
@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event)
{
   Environment environment = event.getEnvironment();
   final String loggingFile = environment.getProperty(PROP_LOGGING_FILE);
   if (loggingFile != null)
   {
      System.setProperty(PROP_LOGGER, "FILE");
      try
      {
         System.setProperty("logging.dir", new File(loggingFile).getParent());
      }
      catch (Exception ex)
      {
         System.err.println("Unable to set up logging.dir from logging.file " + loggingFile + ": " +
                            Throwables.getStackTraceAsString(ex));
      }
   }
   if (environment.containsProperty("debug") &&
       !"false".equalsIgnoreCase(environment.getProperty("debug", String.class)))
   {
      System.setProperty(PROP_SPRING_BOOT_LOG_LEVEL, "DEBUG");
   }
   setProccessId();

}
 
源代码4 项目: Milkomeda   文件: SourcesLogApplicationListener.java
@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
    ConfigurableEnvironment environment = event.getEnvironment();
    if (environment.getClass() == StandardEnvironment.class) {
        return;
    }

    // StandardServletEnvironment or StandardReactiveEnvironment
    // 绑定类型
    boolean logEnable = Binder.get(environment).bind("milkomeda.show-log", Boolean.class).orElseGet(() -> false);
    log.info("milkomeda log is {}", logEnable ? "enable" : "disable");
    log.info("Load sources: {}", environment.getPropertySources());
}
 
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
	ConfigurableEnvironment environment = event.getEnvironment();
	Properties props = new Properties();
	props.put("server.servlet.register-default-servlet", "false");
	props.put("spring.aop.proxy-target-class", "false");
	environment.getPropertySources().addFirst(new PropertiesPropertySource("native", props));
}
 
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
    // 从事件获取 Environment 对象
    ConfigurableEnvironment environment = event.getEnvironment();
    // 调用工具类 PropertySourceUtils 获取 ResourcePropertySource
    ResourcePropertySource propertySource = PropertySourceUtils.getResourcePropertySource("META-INF/listener.properties");
    // 添加至最高优先级
    environment.getPropertySources().addFirst(propertySource);
}
 
源代码7 项目: sofa-tracer   文件: ConfigurationHolderListener.java
@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
    ConfigurableEnvironment environment = event.getEnvironment();
    if (SOFABootEnvUtils.isSpringCloudBootstrapEnvironment(environment)) {
        return;
    }
    SofaTracerProperties sofaTracerProperties = new SofaTracerProperties();
    sofaTracerProperties.setDisableDigestLog(SofaTracerConfiguration
        .getProperty(SofaTracerConfiguration.DISABLE_MIDDLEWARE_DIGEST_LOG_KEY));
    sofaTracerProperties.setDisableConfiguration(SofaTracerConfiguration
        .getMapEmptyIfNull(SofaTracerConfiguration.DISABLE_DIGEST_LOG_KEY));
    sofaTracerProperties.setTracerGlobalRollingPolicy(SofaTracerConfiguration
        .getProperty(SofaTracerConfiguration.TRACER_GLOBAL_ROLLING_KEY));
    sofaTracerProperties.setTracerGlobalLogReserveDay(SofaTracerConfiguration
        .getProperty(SofaTracerConfiguration.TRACER_GLOBAL_LOG_RESERVE_DAY));
    sofaTracerProperties.setStatLogInterval(SofaTracerConfiguration
        .getProperty(SofaTracerConfiguration.STAT_LOG_INTERVAL));
    sofaTracerProperties.setBaggageMaxLength(SofaTracerConfiguration
        .getProperty(SofaTracerConfiguration.TRACER_PENETRATE_ATTRIBUTE_MAX_LENGTH));
    sofaTracerProperties.setSamplerName(SofaTracerConfiguration
        .getProperty(SofaTracerConfiguration.SAMPLER_STRATEGY_NAME_KEY));
    sofaTracerProperties.setSamplerCustomRuleClassName(SofaTracerConfiguration
        .getProperty(SofaTracerConfiguration.SAMPLER_STRATEGY_CUSTOM_RULE_CLASS_NAME));
    String property = SofaTracerConfiguration
        .getProperty(SofaTracerConfiguration.SAMPLER_STRATEGY_PERCENTAGE_KEY);
    sofaTracerProperties
        .setSamplerPercentage(Float.valueOf(StringUtils.isBlank(property) ? "100" : property));
    ConfigurationHolder.setSofaTracerProperties(sofaTracerProperties);
}
 
@Bean
@Lazy(false)
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
  try {
    String foundProperty = null;
    Object p = null;
    ConfigurableEnvironment env = (event != null) ? event.getEnvironment() : null;
    if (env != null) {
      // See if any of the variations of the property name exist in the environment
      for (String timeoutProperty : timeoutProperties) {
        p = env.getProperty(timeoutProperty);
        if (p != null) {
          foundProperty = timeoutProperty;
          break;
        }
      }

      // If the user has not given any specific value for this attribute, force the new default.
      if (foundProperty == null) {
        Properties props = new Properties();
        props.put(timeoutProperties[0], defaultReceiveTimeout);
        env.getPropertySources().addFirst(new PropertiesPropertySource(this.getClass().getName(), props));
      } 
    }
  }
  catch (Throwable e) {
    // If there are any errors (there shouldn't be, but just for safety here), then ignore them.
  }
}
 
@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
    ConfigurableEnvironment envi = event.getEnvironment();
    MutablePropertySources mps = envi.getPropertySources();
    for (PropertySource<?> ps : mps) {
        System.out.println("SpringBoot对应Enviroment已经准备完毕,但此时上下文Context还没有创建,得到PropertySource-->" + ps);
    }
}
 
源代码10 项目: c2mon   文件: C2monApplicationListener.java
@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
  ConfigurableEnvironment environment = event.getEnvironment();
  String propertySource = environment.getProperty("c2mon.client.conf.url");

  if (propertySource != null) {
    try {
      environment.getPropertySources().addAfter("systemEnvironment", new ResourcePropertySource(propertySource));
    } catch (IOException e) {
      throw new RuntimeException("Could not read property source", e);
    }
  }
}
 
源代码11 项目: c2mon   文件: CommonModule.java
/**
 * Listens for the {@link ApplicationEnvironmentPreparedEvent} and injects
 * ${c2mon.server.properties} into the environment with the highest precedence
 * (if it exists). This is in order to allow users to point to an external
 * properties file via ${c2mon.server.properties}.
 */
@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
  ConfigurableEnvironment environment = event.getEnvironment();
  String propertySource = environment.getProperty("c2mon.server.properties");

  if (propertySource != null) {
    try {
      environment.getPropertySources().addAfter("systemEnvironment", new ResourcePropertySource(propertySource));
    } catch (IOException e) {
      throw new RuntimeException("Could not read property source", e);
    }
  }
}
 
@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...");
}
 
@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
	ConfigurableEnvironment environment = event.getEnvironment();
	if (!environment.getProperty("spring.cloud.bootstrap.enabled", Boolean.class,
			true)) {
		return;
	}
	// don't listen to events in a bootstrap context
	if (environment.getPropertySources().contains(BOOTSTRAP_PROPERTY_SOURCE_NAME)) {
		return;
	}
	ConfigurableApplicationContext context = null;
	String configName = environment
			.resolvePlaceholders("${spring.cloud.bootstrap.name:bootstrap}");
	for (ApplicationContextInitializer<?> initializer : event.getSpringApplication()
			.getInitializers()) {
		if (initializer instanceof ParentContextApplicationContextInitializer) {
			context = findBootstrapContext(
					(ParentContextApplicationContextInitializer) initializer,
					configName);
		}
	}
	if (context == null) {
		context = bootstrapServiceContext(environment, event.getSpringApplication(),
				configName);
		event.getSpringApplication()
				.addListeners(new CloseContextOnFailureApplicationListener(context));
	}

	apply(context, event.getSpringApplication(), environment);
}
 
@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
	ConfigurableEnvironment environment = event.getEnvironment();
	if (!environment.resolvePlaceholders("${spring.cloud.config.enabled:false}")
			.equalsIgnoreCase("true")) {
		if (!environment.getPropertySources()
				.contains(this.propertySource.getName())) {
			environment.getPropertySources().addLast(this.propertySource);
		}
	}
}
 
@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
	this.environment = event.getEnvironment();
	Iterable<CloudProfileProvider> cloudProfileProviders = ServiceLoader.load(CloudProfileProvider.class);

	if (ignoreFromSystemProperty()
			|| ignoreFromEnvironmentVariable()
			|| cloudProfilesAlreadySet(cloudProfileProviders)) {
		return;
	}

	boolean addedCloudProfile = false;
	boolean addedKubernetesProfile = false;
	for (CloudProfileProvider cloudProfileProvider : cloudProfileProviders) {
		if (cloudProfileProvider.isCloudPlatform(environment)) {
			String profileToAdd = cloudProfileProvider.getCloudProfile();
			if (!Arrays.asList(environment.getActiveProfiles()).contains(profileToAdd)) {
				if (profileToAdd.equals(KubernetesCloudProfileProvider.PROFILE)) {
					addedKubernetesProfile = true;
				}
				environment.addActiveProfile(profileToAdd);
				addedCloudProfile = true;
			}
		}
	}
	if (!addedKubernetesProfile) {
		Map<String, Object> properties = new LinkedHashMap<>();
		properties.put("spring.cloud.kubernetes.enabled", false);
		logger.info("Setting property 'spring.cloud.kubernetes.enabled' to false.");
		MutablePropertySources propertySources = environment.getPropertySources();
		if (propertySources != null) {
			if (propertySources.contains(
					CommandLinePropertySource.COMMAND_LINE_PROPERTY_SOURCE_NAME)) {
				propertySources.addAfter(
						CommandLinePropertySource.COMMAND_LINE_PROPERTY_SOURCE_NAME,
						new MapPropertySource("skipperProfileApplicationListener", properties));
			}
			else {
				propertySources
						.addFirst(new MapPropertySource("skipperProfileApplicationListener", properties));
			}
		}
	}
	if (!addedCloudProfile) {
		environment.addActiveProfile("local");
	}
}
 
protected void onApplicationEnvironmentPreparedEvent(
		@NonNull ApplicationEnvironmentPreparedEvent environmentPreparedEvent) {

	Assert.notNull(environmentPreparedEvent, "ApplicationEnvironmentPreparedEvent must not be null");

	Environment environment = environmentPreparedEvent.getEnvironment();

	if (isSystemPropertyNotSet(SPRING_BOOT_DATA_GEMFIRE_LOG_LEVEL_PROPERTY)) {

		String logLevel = environment.getProperty(SPRING_BOOT_DATA_GEMFIRE_LOG_LEVEL_PROPERTY,
			environment.getProperty(SPRING_DATA_GEMFIRE_LOGGING_LOG_LEVEL,
			environment.getProperty(SPRING_DATA_GEMFIRE_CACHE_LOG_LEVEL)));

		setSystemProperty(SPRING_BOOT_DATA_GEMFIRE_LOG_LEVEL_PROPERTY, logLevel);
	}
}
 
@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
    ConfigurableEnvironment environment = event.getEnvironment();
    addKubernetesProfile(environment);
}
 
@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
	this.environment = event.getEnvironment();
	Iterable<CloudProfileProvider> cloudProfileProviders = ServiceLoader.load(CloudProfileProvider.class);

	if (ignoreFromSystemProperty()
			|| ignoreFromEnvironmentVariable()
			|| cloudProfilesAlreadySet(cloudProfileProviders)) {
		return;
	}

	boolean addedCloudProfile = false;
	boolean addedKubernetesProfile = false;
	for (CloudProfileProvider cloudProfileProvider : cloudProfileProviders) {
		if (cloudProfileProvider.isCloudPlatform(environment)) {
			String profileToAdd = cloudProfileProvider.getCloudProfile();
			if (!Arrays.asList(environment.getActiveProfiles()).contains(profileToAdd)) {
				if (profileToAdd.equals(KubernetesCloudProfileProvider.PROFILE)) {
					addedKubernetesProfile = true;
				}
				environment.addActiveProfile(profileToAdd);
				addedCloudProfile = true;
			}
		}
	}

	if (!addedKubernetesProfile) {
		Map<String, Object> properties = new LinkedHashMap<>();
		properties.put("spring.cloud.kubernetes.enabled", false);
		logger.info("Setting property 'spring.cloud.kubernetes.enabled' to false.");
		MutablePropertySources propertySources = environment.getPropertySources();
		if (propertySources != null) {
			if (propertySources.contains(
					CommandLinePropertySource.COMMAND_LINE_PROPERTY_SOURCE_NAME)) {
				propertySources.addAfter(
						CommandLinePropertySource.COMMAND_LINE_PROPERTY_SOURCE_NAME,
						new MapPropertySource("skipperProfileApplicationListener", properties));
			}
			else {
				propertySources
						.addFirst(new MapPropertySource("skipperProfileApplicationListener", properties));
			}
		}
	}

	if (!addedCloudProfile) {
		environment.addActiveProfile("local");
	}

}