Java Code Examples for org.springframework.context.event.ContextRefreshedEvent#getApplicationContext()

The following examples show how to use org.springframework.context.event.ContextRefreshedEvent#getApplicationContext() . 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: SofaDashboardContextRefreshedListener.java    From sofa-dashboard-client with Apache License 2.0 6 votes vote down vote up
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
    ApplicationContext context = event.getApplicationContext();
    ReadinessCheckListener readinessCheckListener = context
        .getBean(ReadinessCheckListener.class);
    AppPublisher publisher = context.getBean(AppPublisher.class);

    try {
        String status = readinessCheckListener.getHealthCheckerStatus() ? Status.UP.toString()
            : Status.DOWN.toString();
        publisher.getApplication().setAppState(status);
        publisher.start();
        publisher.register();
    } catch (Exception e) {
        LOGGER.info("sofa dashboard client register failed.", e);
    }
}
 
Example 2
Source File: EurekaStore.java    From qconfig with MIT License 6 votes vote down vote up
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
    ApplicationContext applicationContext = event.getApplicationContext();
    if (applicationContext.getParent() != null) {
        return;
    }

    logger.info("init eureka store");
    try {
        context = (WebApplicationContext) applicationContext;

        initEurekaEnvironment();
        initEurekaServerContext();

        ServletContext sc = context.getServletContext();
        sc.setAttribute(EurekaServerContext.class.getName(), serverContext);
    } catch (Throwable e) {
        logger.error("Cannot bootstrap eureka server :", e);
        throw new RuntimeException("Cannot bootstrap eureka server :", e);
    }
}
 
Example 3
Source File: DcsSchedulingConfiguration.java    From schedule-spring-boot-starter with Apache License 2.0 6 votes vote down vote up
@Override
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
    try {
        ApplicationContext applicationContext = contextRefreshedEvent.getApplicationContext();
        //1. 初始化配置
        init_config(applicationContext);
        //2. 初始化服务
        init_server(applicationContext);
        //3. 启动任务
        init_task(applicationContext);
        //4. 挂载节点
        init_node();
        //5. 心跳监听
        HeartbeatService.getInstance().startFlushScheduleStatus();
        logger.info("itstack middleware schedule init config、server、task、node、heart done!");
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 4
Source File: PostProxyInvokerContextListener.java    From Spring with Apache License 2.0 6 votes vote down vote up
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
	final ApplicationContext context = event.getApplicationContext();
	final String[] beanDefinitionNames = context.getBeanDefinitionNames();
	for(String beanName : beanDefinitionNames){
		final BeanDefinition beanDefinition = factory.getBeanDefinition(beanName);
		final String originalClassName = beanDefinition.getBeanClassName();
		try {
			final Class<?> originalClass = Class.forName(originalClassName);
			final Method[] methods = originalClass.getMethods();
			for(Method method : methods){
				if(method.isAnnotationPresent(PostProxy.class)){
					final Object bean = context.getBean(beanName);
					final Method currentMethod = bean.getClass().getMethod(method.getName(), method.getParameterTypes());
					currentMethod.invoke(bean);
				}
			}
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}
}
 
Example 5
Source File: DeferredApplicationEventPublisher.java    From nacos-spring-project with Apache License 2.0 5 votes vote down vote up
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {

	ApplicationContext currentContext = event.getApplicationContext();

	if (!currentContext.equals(context)) {
		// prevent multiple event multi-casts in hierarchical contexts
		return;
	}

	replayDeferredEvents();
}
 
Example 6
Source File: SpringPostProcessor.java    From distributed-transaction-process with MIT License 5 votes vote down vote up
@Override
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
    ApplicationContext applicationContext = contextRefreshedEvent.getApplicationContext();

    if (applicationContext.getParent() == null) {
        FactoryBuilder.registerBeanFactory(applicationContext.getBean(BeanFactory.class));
    }
}
 
Example 7
Source File: ApplicationContextListener.java    From jwala with Apache License 2.0 5 votes vote down vote up
/**
 * Implementation of the spring event listener interface.
 *
 * @param event the spring event from the application
 */
@EventListener
public void handleEvent(ApplicationEvent event) {
    // checking for start up event
    // order of events is BrokerAvailabilityEvent -> ContextRefreshedEvent[parent=null] -> ContextRefreshedEvent[with non-null parent]
    // so wait until the latest event is received: ContextRefreshedEvent[with non-null parent]

    // skip the BrokerAvailabilityEvent, and ignore all other events (SessionConnectedEvent, ServletRequestHandledEvent, ContextClosedEvent, etc.)
    if (!(event instanceof ContextRefreshedEvent)) {
        LOGGER.debug("Expecting ContextRefreshedEvent. Skipping.");
        return;
    }

    LOGGER.info("Received ContextRefreshedEvent {}", event);

    ContextRefreshedEvent crEvent = (ContextRefreshedEvent) event;
    final ApplicationContext applicationContext = crEvent.getApplicationContext();
    // skip the ContextRefreshedEvent[parent=null] but check for non-null context first
    if (null == applicationContext) {
        LOGGER.debug("Expecting non-null ApplicationContext. Skipping.");
        return;
    }
    if (null == applicationContext.getParent()) {
        LOGGER.debug("Expecting non-null ApplicationContext parent. Skipping.");
        return;
    }

    processBootstrapConfiguration();
}
 
Example 8
Source File: ConfigListener.java    From anyline with Apache License 2.0 5 votes vote down vote up
@Override 
public void onApplicationEvent(ContextRefreshedEvent event) { 
	if (event.getApplicationContext().getParent() != null) { 
		return; 
	} 
	ApplicationContext app = event.getApplicationContext(); 
	if (app instanceof WebApplicationContext) { 
		WebApplicationContext webApplicationContext = (WebApplicationContext) app; 
		ServletContext servlet = webApplicationContext.getServletContext(); 
		Map<String, String> configs = ConfigTable.getConfigs(); 
		String key = ConfigTable.getString("SERVLET_ATTRIBUTE_KEY", "al"); 
		servlet.setAttribute(key, configs); 
		log.warn("[配置文件加载至servlet context][key:{}]",key); 
	} 
}
 
Example 9
Source File: AbstractServerConfigurationBean.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void onApplicationEvent(ApplicationEvent event)
{
    if (event instanceof ContextRefreshedEvent)
    {
        ContextRefreshedEvent refreshEvent = (ContextRefreshedEvent)event;
        ApplicationContext refreshContext = refreshEvent.getApplicationContext();
        if (refreshContext != null && refreshContext.equals(applicationContext))
        {
            // Initialize the bean
          
            init();
        }
    }
}
 
Example 10
Source File: ScheduledAnnotationBeanPostProcessor.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
	if (event.getApplicationContext() == this.applicationContext) {
		// Running in an ApplicationContext -> register tasks this late...
		// giving other ContextRefreshedEvent listeners a chance to perform
		// their work at the same time (e.g. Spring Batch's job registration).
		finishRegistration();
	}
}
 
Example 11
Source File: SystemEntityTypeI18nInitializer.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Initialize internationalization attributes
 *
 * @param event application event
 */
public void initialize(ContextRefreshedEvent event) {
  ApplicationContext ctx = event.getApplicationContext();
  Stream<String> languageCodes = LanguageService.getLanguageCodes();

  EntityTypeMetadata entityTypeMeta = ctx.getBean(EntityTypeMetadata.class);
  AttributeMetadata attrMetaMeta = ctx.getBean(AttributeMetadata.class);
  L10nStringMetadata l10nStringMeta = ctx.getBean(L10nStringMetadata.class);

  languageCodes.forEach(
      languageCode -> {
        entityTypeMeta
            .addAttribute(getI18nAttributeName(EntityTypeMetadata.LABEL, languageCode))
            .setNillable(true)
            .setLabel("Label (" + languageCode + ')');
        entityTypeMeta
            .addAttribute(getI18nAttributeName(EntityTypeMetadata.DESCRIPTION, languageCode))
            .setNillable(true)
            .setLabel("Description (" + languageCode + ')')
            .setDataType(TEXT);
        attrMetaMeta
            .addAttribute(getI18nAttributeName(AttributeMetadata.LABEL, languageCode))
            .setNillable(true)
            .setLabel("Label (" + languageCode + ')');
        attrMetaMeta
            .addAttribute(getI18nAttributeName(AttributeMetadata.DESCRIPTION, languageCode))
            .setNillable(true)
            .setLabel("Description (" + languageCode + ')')
            .setDataType(TEXT);
        l10nStringMeta.addAttribute(languageCode).setNillable(true).setDataType(TEXT);
      });
}
 
Example 12
Source File: CloudbreakCleanupService.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
    heartbeatService.heartbeat();
    try {
        restartFlowService.purgeTerminatedResourceFlowLogs();
    } catch (Exception e) {
        LOGGER.error("Clean up or the migration operations failed. Shutting down the node. ", e);
        ConfigurableApplicationContext applicationContext = (ConfigurableApplicationContext) event.getApplicationContext();
        applicationContext.close();
    }
}
 
Example 13
Source File: SystemEntityPopulator.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
void populate(ContextRefreshedEvent event) {
  // discover system entity registries
  ApplicationContext applicationContext = event.getApplicationContext();
  SystemEntityRegistry systemEntityRegistry =
      applicationContext.getBean(SystemEntityRegistry.class);
  populate(systemEntityRegistry);
}
 
Example 14
Source File: ManagementContextResolverBootstrap.java    From thinking-in-spring-boot-samples with Apache License 2.0 5 votes vote down vote up
@EventListener(ContextRefreshedEvent.class)
public void onContextRefreshedEvent(ContextRefreshedEvent event) {
    ApplicationContext currentApplicationContext = event.getApplicationContext();
    if (currentApplicationContext.equals(applicationContext)) { // 当应用上下文来自于服务端时
        System.out.printf("当前应用上下文 ID :%s 执行 onContextRefreshedEvent() 方法\n",
                currentApplicationContext.getId());
    }
}
 
Example 15
Source File: MQAutoConfiguration.java    From elephant with Apache License 2.0 4 votes vote down vote up
@Override
public synchronized void onApplicationEvent(ContextRefreshedEvent event) {
	if(isRepeat){
		return;
	}
	this.isRepeat = true;
	this.applicationContext = event.getApplicationContext();
	for(String beanName : this.applicationContext.getBeanDefinitionNames()){
		Class<?> clz = this.applicationContext.getType(beanName);
		if(clz == null) continue;
		Method[] methods = ReflectionUtils.getAllDeclaredMethods(clz);
		if(methods == null || methods.length <= 0){
			continue;
		}
		for(Method method : methods){
			QueueListener queueListener = AnnotationUtils.findAnnotation(method, QueueListener.class);
			String registerBeanName = null;
			String retryRegisterBeanName = null;
			if(queueListener != null){
				registerBeanName = "queueConsumer" + count.getAndIncrement();
				this.registerListener(
						registerBeanName, 
						new ActiveMQQueue(queueListener.name()),
						this.applicationContext.getBean(beanName),
						method,
						queueListener.retryTimes(),
						false);
				retryRegisterBeanName = "retryQueueConsumer" + count.getAndIncrement();
				this.registerListener(
						retryRegisterBeanName, 
						new ActiveMQQueue(queueListener.name() + MQConstant.RETRY_QUEUE_SUFFIX),
						this.applicationContext.getBean(beanName),
						method,
						0,
						true);
			}
			TopicListnener topicListnener = AnnotationUtils.findAnnotation(method, TopicListnener.class);
			if(topicListnener != null){
				registerBeanName = "topicConsumer" + count.getAndIncrement();
				this.registerListener(
						registerBeanName, 
						new ActiveMQTopic(topicListnener.name()), 
						this.applicationContext.getBean(beanName),
						method,
						topicListnener.retryTimes(),
						false);
				retryRegisterBeanName = "retryTopicConsumer" + count.getAndIncrement();
				this.registerListener(
						retryRegisterBeanName, 
						new ActiveMQTopic(topicListnener.name() + MQConstant.RETRY_QUEUE_SUFFIX),
						this.applicationContext.getBean(beanName),
						method,
						0,
						true);
			}
			start(registerBeanName);
			start(retryRegisterBeanName);
		}
	}
}
 
Example 16
Source File: RegionTemplateAutoConfiguration.java    From spring-boot-data-geode with Apache License 2.0 4 votes vote down vote up
@EventListener({ ContextRefreshedEvent.class })
public void regionTemplateContextRefreshedEventListener(ContextRefreshedEvent event) {

	this.regionNamesWithTemplates.clear();

	ApplicationContext applicationContext = event.getApplicationContext();

	if (applicationContext instanceof ConfigurableApplicationContext) {

		ConfigurableApplicationContext configurableApplicationContext =
			(ConfigurableApplicationContext) applicationContext;

		GemFireCache cache = configurableApplicationContext.getBean(GemFireCache.class);

		registerRegionTemplatesForCacheRegions(configurableApplicationContext, cache);
	}
}
 
Example 17
Source File: SettingsPopulator.java    From molgenis with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void initialize(ContextRefreshedEvent event) {
  ApplicationContext ctx = event.getApplicationContext();
  ctx.getBeansOfType(DefaultSettingsEntityType.class).values().forEach(this::initialize);
}
 
Example 18
Source File: ImportServiceRegistrar.java    From molgenis with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void register(ContextRefreshedEvent event) {
  ApplicationContext ctx = event.getApplicationContext();
  Map<String, ImportService> importServiceMap = ctx.getBeansOfType(ImportService.class);
  importServiceMap.values().forEach(this::register);
}
 
Example 19
Source File: JobFactoryRegistrar.java    From molgenis with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void register(ContextRefreshedEvent event) {
  ApplicationContext ctx = event.getApplicationContext();
  Map<String, JobFactory> jobFactoryMap = ctx.getBeansOfType(JobFactory.class);
  jobFactoryMap.values().forEach(this::register);
}
 
Example 20
Source File: ApplicationStartUp.java    From mywx with Apache License 2.0 3 votes vote down vote up
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
    ApplicationContext context = event.getApplicationContext();


    // WxMpMessageRouter router = context.getBean(WxMpMessageRouter.class);


}