org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent Java Examples

The following examples show how to use org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent. 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: ApplicationEventListener.java    From SpringBoot-Base-System with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 应用程序启动过程监听
 * 
 * @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 {
	}
}
 
Example #3
Source File: ContainerApplication.java    From tac with MIT License 6 votes vote down vote up
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);
    }
 
Example #4
Source File: WelcomeLogoApplicationListener.java    From dubbo-spring-boot-project with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #5
Source File: ConfigFileValidationApplicationListener.java    From circus-train with Apache License 2.0 6 votes vote down vote up
@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);
  }
}
 
Example #6
Source File: KafDrop.java    From Kafdrop with Apache License 2.0 6 votes vote down vote up
@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();

}
 
Example #7
Source File: ApplicationEventListener.java    From Almost-Famous with MIT License 6 votes vote down vote up
@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("应用关闭");
    }

}
 
Example #8
Source File: ApplicationEventListener.java    From Almost-Famous with MIT License 6 votes vote down vote up
@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 {

    }
}
 
Example #9
Source File: ApplicationEventListener.java    From Almost-Famous with MIT License 6 votes vote down vote up
@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("应用关闭");
    }
}
 
Example #10
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 #11
Source File: PropertiesListener.java    From TarsJava with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@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();
            }
        }
    }
}
 
Example #12
Source File: C2monApplicationListener.java    From c2mon with GNU Lesser General Public License v3.0 5 votes vote down vote up
@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);
    }
  }
}
 
Example #13
Source File: ApplicationEnvironmentPreparedListener.java    From sofa-rpc-boot-projects with Apache License 2.0 5 votes vote down vote up
@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);
        }
    }
}
 
Example #14
Source File: GeodeLoggingApplicationListenerUnitTests.java    From spring-boot-data-geode with Apache License 2.0 5 votes vote down vote up
@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));
}
 
Example #15
Source File: DubboBannerApplicationListener.java    From dubbo-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
@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);
  }
}
 
Example #16
Source File: ApplicationEnvironmentPreparedEventListener.java    From seed with Apache License 2.0 5 votes vote down vote up
@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);
    }
}
 
Example #17
Source File: SourcesLogApplicationListener.java    From Milkomeda with MIT License 5 votes vote down vote up
@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());
}
 
Example #18
Source File: CommonModule.java    From c2mon with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 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);
    }
  }
}
 
Example #19
Source File: ExampleApplicationListener.java    From building-microservices with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #20
Source File: LatticeCloudApplicationListener.java    From spring-cloud-lattice with Apache License 2.0 5 votes vote down vote up
@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
	if (!event.getEnvironment().resolvePlaceholders("${PROCESS_GUID:}").equals("")) {
		event.getEnvironment().addActiveProfile("cloud");
		event.getEnvironment().addActiveProfile("lattice");
	}
}
 
Example #21
Source File: OsiamHome.java    From osiam with MIT License 5 votes vote down vote up
@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();
    }
}
 
Example #22
Source File: SsoServiceCredentialsListener.java    From spring-cloud-sso-connector with Apache License 2.0 5 votes vote down vote up
@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);
        }
    }
}
 
Example #23
Source File: EnvironmentPreparedEventApplicationListener.java    From micro-service with MIT License 5 votes vote down vote up
@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...");
}
 
Example #24
Source File: BootstrapApplicationListener.java    From spring-cloud-commons with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #25
Source File: DefaultThreadUncaughtExceptionHandler.java    From kork with Apache License 2.0 5 votes vote down vote up
@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
  boolean isEnabled =
      event.getEnvironment().getProperty("globalExceptionHandlingEnabled", boolean.class, true);

  if (isEnabled) {
    priorHandler = Thread.getDefaultUncaughtExceptionHandler();
    Thread.setDefaultUncaughtExceptionHandler(this);
  }
}
 
Example #26
Source File: SpringBoot1CompatibilityApplicationListener.java    From kork with Apache License 2.0 5 votes vote down vote up
@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
  // Allow extensions to override bean definitions in OSS projects.
  setIfMissing("spring.main.allow-bean-definition-overriding", "true");

  // Put spring endpoints on / instead of /actuator (for /health backwards compat).
  setIfMissing("management.endpoints.web.base-path", "/");
}
 
Example #27
Source File: ConfigServerBootstrapApplicationListener.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
@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);
		}
	}
}
 
Example #28
Source File: SoulLogo.java    From soul with Apache License 2.0 5 votes vote down vote up
@Override
public void onApplicationEvent(final ApplicationEnvironmentPreparedEvent event) {
    if (!alreadyLog.compareAndSet(false, true)) {
        return;
    }
    log.info(buildBannerText());
}
 
Example #29
Source File: MQConfigurationListenerDefault.java    From mq-jms-spring with Apache License 2.0 5 votes vote down vote up
@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.
  }
}
 
Example #30
Source File: DubboRegistryZooKeeperProviderBootstrap.java    From spring-boot-tutorial with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
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);
}