下面列出了怎么用org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent的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);
}
}
}
@Override
public void onApplicationEvent(ApplicationEvent event) {
if (event instanceof ApplicationEnvironmentPreparedEvent) {
LOGGER.debug("初始化环境变量");
} else if (event instanceof ApplicationPreparedEvent) {
LOGGER.debug("初始化完成");
} else if (event instanceof ContextRefreshedEvent) {
LOGGER.debug("应用刷新");
} else if (event instanceof ApplicationReadyEvent) {
LOGGER.debug("应用已启动完成");
} else if (event instanceof ContextStartedEvent) {
LOGGER.debug("应用启动,需要在代码动态添加监听器才可捕获");
} else if (event instanceof ContextStoppedEvent) {
LOGGER.debug("应用停止");
} else if (event instanceof ContextClosedEvent) {
ApplicationContext applicationContext = ((ContextClosedEvent) event).getApplicationContext();
grpcClient = applicationContext.getBean(GrpcClient.class);
grpcClient.close();
LOGGER.debug("应用关闭");
}
}
@Override
public void onApplicationEvent(ApplicationEvent event) {
if (event instanceof ApplicationEnvironmentPreparedEvent) {
LOG.debug("初始化环境变量");
} else if (event instanceof ApplicationPreparedEvent) {
LOG.debug("初始化完成");
LOG.debug("初始GameData策划数据");
ConfigManager.loadGameData(this.configPath);
} else if (event instanceof ContextRefreshedEvent) {
LOG.debug("应用刷新");
} else if (event instanceof ApplicationReadyEvent) {
LOG.debug("应用已启动完成");
} else if (event instanceof ContextStartedEvent) {
LOG.debug("应用启动,需要在代码动态添加监听器才可捕获");
} else if (event instanceof ContextStoppedEvent) {
LOG.debug("应用停止");
} else if (event instanceof ContextClosedEvent) {
ApplicationContext context = ((ContextClosedEvent) event).getApplicationContext();
rpcClient = context.getBean(RpcClient.class);
rpcClient.close();
LOG.error("应用关闭");
} else {
}
}
@Override
public void onApplicationEvent(ApplicationEvent event) {
if (event instanceof ApplicationEnvironmentPreparedEvent) {
LOG.debug("初始化环境变量");
} else if (event instanceof ApplicationPreparedEvent) {
LOG.debug("初始化完成");
LOG.debug("初始GameData策划数据");
String path = ApplicationEventListener.class.getResource("/gamedata").getFile();
ConfigManager.loadGameData(path);
} else if (event instanceof ContextRefreshedEvent) {
LOG.debug("应用刷新");
} else if (event instanceof ApplicationReadyEvent) {
LOG.debug("应用已启动完成");
} else if (event instanceof ContextStartedEvent) {
LOG.debug("应用启动,需要在代码动态添加监听器才可捕获");
} else if (event instanceof ContextStoppedEvent) {
LOG.debug("应用停止");
} else if (event instanceof ContextClosedEvent) {
ApplicationContext applicationContext = ((ContextClosedEvent) event).getApplicationContext();
grpcClient = applicationContext.getBean(GrpcClient.class);
grpcClient.close();
LOG.debug("应用关闭");
}
}
@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
RemotePropertySource sources = event.getSpringApplication()
.getMainApplicationClass().getAnnotation(RemotePropertySource.class);
String configPath = Server.getInstance().getServerConfig().getBasePath() + "/conf/";
if (sources != null) {
for (String name : sources.value()) {
try {
ConfigHelper.getInstance().loadConfig(name);
File config = new File(configPath + name);
if (config.exists()) {
Properties properties = new Properties();
properties.load(new FileInputStream(config));
event.getEnvironment().getPropertySources().addFirst(new PropertiesPropertySource(name, properties));
} else {
throw new RuntimeException("[TARS] load config failed file not exists");
}
} catch (IOException e) {
System.err.println("[TARS] load config failed: " + name);
e.printStackTrace();
}
}
}
}
public static void main(String[] args) throws Exception {
// the code must execute before spring start
JarFile bootJarFile = BootJarLaucherUtils.getBootJarFile();
if (bootJarFile != null) {
BootJarLaucherUtils.unpackBootLibs(bootJarFile);
log.debug("the temp tac lib folder:{}", BootJarLaucherUtils.getTempUnpackFolder());
}
SpringApplication springApplication = new SpringApplication(ContainerApplication.class);
springApplication.setWebEnvironment(true);
springApplication.setBannerMode(Banner.Mode.OFF);
springApplication.addListeners(new ApplicationListener<ApplicationEnvironmentPreparedEvent>() {
@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
CodeLoadService.changeClassLoader(event.getEnvironment());
}
});
springApplication.run(args);
}
@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()));
}
@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
// Skip if processed before, prevent duplicated execution in Hierarchical ApplicationContext
if (processed.get()) {
return;
}
/**
* Gets Logger After LoggingSystem configuration ready
* @see LoggingApplicationListener
*/
final Logger logger = LoggerFactory.getLogger(getClass());
String bannerText = buildBannerText();
if (logger.isInfoEnabled()) {
logger.info(bannerText);
} else {
System.out.print(bannerText);
}
// mark processed to be true
processed.compareAndSet(false, true);
}
/**
* 应用程序启动过程监听
*
* @time 2018年4月10日 下午5:05:33
* @version V1.0
* @param event
*/
@Override
public void onApplicationEvent(ApplicationEvent event) {
// 在这里可以监听到Spring Boot的生命周期
if (event instanceof ApplicationEnvironmentPreparedEvent) { // 初始化环境变量
log.debug("初始化环境变量");
} else if (event instanceof ApplicationPreparedEvent) { // 初始化完成
log.debug("初始化环境变量完成");
} else if (event instanceof ContextRefreshedEvent) { // 应用刷新,当ApplicationContext初始化或者刷新时触发该事件。
log.debug("应用刷新");
} else if (event instanceof ApplicationReadyEvent) {// 应用已启动完成
log.debug("应用已启动完成");
} else if (event instanceof ContextStartedEvent) { // 应用启动,Spring2.5新增的事件,当容器调用ConfigurableApplicationContext的
// Start()方法开始/重新开始容器时触发该事件。
log.debug("应用启动");
} else if (event instanceof ContextStoppedEvent) { // 应用停止,Spring2.5新增的事件,当容器调用ConfigurableApplicationContext
// 的Stop()方法停止容器时触发该事件。
log.debug("应用停止");
} else if (event instanceof ContextClosedEvent) { // 应用关闭,当ApplicationContext被关闭时触发该事件。容器被关闭时,其管理的所有
// 单例Bean都被销毁。
log.debug("应用关闭");
} else {
}
}
@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
String configFilesString = event.getEnvironment().getProperty("spring.config.location");
List<String> errors = new ArrayList<>();
if (StringUtils.isBlank(configFilesString)) {
errors.add("No config file was specified.");
} else {
for (String configFileString : Splitter.on(',').split(configFilesString)) {
File configFile = new File(configFileString);
if (!configFile.exists()) {
errors.add("Config file " + configFileString + " does not exist.");
} else if (!configFile.isFile()) {
errors.add("Config file " + configFileString + " is a directory.");
} else if (!configFile.canRead()) {
errors.add("Config file " + configFileString + " cannot be read.");
}
}
}
if (!errors.isEmpty()) {
throw new ConfigFileValidationException(errors);
}
}
@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();
}
@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));
}
@Override
public void onApplicationEvent(ApplicationEvent event) {
if (event instanceof ApplicationStartingEvent) {
onApplicationStartingEvent((ApplicationStartingEvent) event);
}
else if (event instanceof ApplicationEnvironmentPreparedEvent) {
onApplicationEnvironmentPreparedEvent(
(ApplicationEnvironmentPreparedEvent) event);
}
}
public static void main(String[] args) {
new SpringApplicationBuilder(DubboRegistryZooKeeperProviderBootstrap.class)
.listeners((ApplicationListener<ApplicationEnvironmentPreparedEvent>) event -> {
Environment environment = event.getEnvironment();
int port = environment.getProperty("embedded.zookeeper.port", int.class);
new EmbeddedZooKeeper(port, false).start();
})
.run(args);
}
@Override
public void onApplicationEvent(final ApplicationEnvironmentPreparedEvent event) {
if (!alreadyLog.compareAndSet(false, true)) {
return;
}
log.info(buildBannerText());
}
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
// 从事件获取 Environment 对象
ConfigurableEnvironment environment = event.getEnvironment();
// 调用工具类 PropertySourceUtils 获取 ResourcePropertySource
ResourcePropertySource propertySource = PropertySourceUtils.getResourcePropertySource("META-INF/listener.properties");
// 添加至最高优先级
environment.getPropertySources().addFirst(propertySource);
}
@Override
public void onApplicationEvent(ApplicationEvent event) {
if (event instanceof ApplicationEnvironmentPreparedEvent) {
onApplicationEvent((ApplicationEnvironmentPreparedEvent) event);
} else if (event instanceof ApplicationPreparedEvent) {
onApplicationEvent((ApplicationPreparedEvent) event);
}
}
@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(ApplicationEvent event) {
if (event instanceof ApplicationEnvironmentPreparedEvent) {
Environment env = ((ApplicationEnvironmentPreparedEvent) event).getEnvironment();
String defaultTracer = env.getProperty(SofaBootRpcProperties.PREFIX + ".defaultTracer");
if (defaultTracer != null) {
RpcConfigs.putValue(RpcOptions.DEFAULT_TRACER, defaultTracer);
}
}
}
@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);
}
}
@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
if (BANNER_MODE == Banner.Mode.OFF) {
return;
}
String bannerText = this.buildBannerText();
if (BANNER_MODE == Mode.CONSOLE) {
System.out.print(bannerText);
} else if (BANNER_MODE == Mode.LOG) {
logger.info(bannerText);
}
}
@Test
public void onApplicationEventWithApplicationEnvironmentPreparedEventProcessesEvent() {
doNothing().when(this.listener)
.onApplicationEnvironmentPreparedEvent(any(ApplicationEnvironmentPreparedEvent.class));
this.listener.onApplicationEvent(this.mockEvent);
verify(this.listener, times(1))
.onApplicationEnvironmentPreparedEvent(eq(this.mockEvent));
}
@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);
}
}
}
/**
* 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) {
System.err.println("Adding extra properties");
PropertySource<?> propertySource = new MapPropertySource("example",
Collections.singletonMap("example.secret", "the-secret-key"));
event.getEnvironment().getPropertySources().addFirst(propertySource);
}
@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
if (!event.getEnvironment().resolvePlaceholders("${PROCESS_GUID:}").equals("")) {
event.getEnvironment().addActiveProfile("cloud");
event.getEnvironment().addActiveProfile("lattice");
}
}
@Override
public void onApplicationEvent(ApplicationEvent event) {
if (event instanceof ApplicationEnvironmentPreparedEvent) {
ConfigurableEnvironment environment = ((ApplicationEnvironmentPreparedEvent) event).getEnvironment();
configure(environment);
if(shouldInitializeHome) {
initialize();
}
} else if (event instanceof ApplicationPreparedEvent) {
writeLogs();
}
}
@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
if (cloud != null) return;
try {
cloud = new CloudFactory().getCloud();
} catch (CloudException e) {
return; // not running on a known cloud environment, so nothing to do
}
for (ServiceInfo serviceInfo : cloud.getServiceInfos()) {
if (serviceInfo instanceof SsoServiceInfo) {
Map<String, Object> map = new HashMap<>();
SsoServiceInfo ssoServiceInfo = (SsoServiceInfo) serviceInfo;
map.put("security.oauth2.client.clientId", ssoServiceInfo.getClientId());
map.put("security.oauth2.client.clientSecret", ssoServiceInfo.getClientSecret());
map.put("security.oauth2.client.accessTokenUri", ssoServiceInfo.getAuthDomain() + "/oauth/token");
map.put("security.oauth2.client.userAuthorizationUri", ssoServiceInfo.getAuthDomain() + "/oauth/authorize");
map.put("ssoServiceUrl", ssoServiceInfo.getAuthDomain());
map.put("security.oauth2.resource.userInfoUri", ssoServiceInfo.getAuthDomain() + "/userinfo");
map.put("security.oauth2.resource.tokenInfoUri", ssoServiceInfo.getAuthDomain() + "/check_token");
map.put("security.oauth2.resource.jwk.key-set-uri", ssoServiceInfo.getAuthDomain() + "/token_keys");
MapPropertySource mapPropertySource = new MapPropertySource("vcapPivotalSso", map);
event.getEnvironment().getPropertySources().addFirst(mapPropertySource);
}
}
}