Java Code Examples for org.springframework.context.ConfigurableApplicationContext#addApplicationListener()

The following examples show how to use org.springframework.context.ConfigurableApplicationContext#addApplicationListener() . These examples are extracted from open source projects. 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
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    // register a context close handler
    if (applicationContext instanceof ConfigurableApplicationContext) {
        ConfigurableApplicationContext context = (ConfigurableApplicationContext) applicationContext;
        context.addApplicationListener(new ApplicationListener<ContextClosedEvent>() {
            @Override
            public void onApplicationEvent(ContextClosedEvent e) {
                LOG.info("Context '" + e.getApplicationContext().getDisplayName() + "' closed, removing registered ApplicationThreadLocals");
                if (!ApplicationThreadLocal.clear()) {
                    LOG.error("Error(s) occurred removing registered ApplicationThreadLocals");
                }
            }
        });
    }
}
 
Example 2
Source Project: blog-tutorials   File: WireMockInitializer.java    License: MIT License 6 votes vote down vote up
@Override
public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
  WireMockServer wireMockServer = new WireMockServer(new WireMockConfiguration().dynamicPort());
  wireMockServer.start();

  configurableApplicationContext.getBeanFactory().registerSingleton("wireMockServer", wireMockServer);

  configurableApplicationContext.addApplicationListener(applicationEvent -> {
    if (applicationEvent instanceof ContextClosedEvent) {
      wireMockServer.stop();
    }
  });

  TestPropertyValues
    .of("todo_url:http://localhost:" + wireMockServer.port() + "/todos")
    .applyTo(configurableApplicationContext);
}
 
Example 3
Source Project: sdn-rx   File: TestContainerInitializer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
	final Neo4jContainer<?> neo4jContainer = new Neo4jContainer<>("neo4j:4.0.0-enterprise")
		.withEnv("NEO4J_ACCEPT_LICENSE_AGREEMENT", "yes");
	neo4jContainer.start();
	configurableApplicationContext
		.addApplicationListener((ApplicationListener<ContextClosedEvent>) event -> neo4jContainer.stop());
	TestPropertyValues
		.of(
			"org.neo4j.driver.uri=" + neo4jContainer.getBoltUrl(),
			"org.neo4j.driver.authentication.username=neo4j",
			"org.neo4j.driver.authentication.password=" + neo4jContainer.getAdminPassword()
		)
		.applyTo(configurableApplicationContext.getEnvironment());
}
 
Example 4
Source Project: sdn-rx   File: TestContainerInitializer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
	final Neo4jContainer<?> neo4jContainer = new Neo4jContainer<>("neo4j:4.0").withoutAuthentication();
	neo4jContainer.start();
	configurableApplicationContext
		.addApplicationListener((ApplicationListener<ContextClosedEvent>) event -> neo4jContainer.stop());
	TestPropertyValues.of("org.neo4j.driver.uri=" + neo4jContainer.getBoltUrl())
		.applyTo(configurableApplicationContext.getEnvironment());
}
 
Example 5
@Override
public void customizeContext(ConfigurableApplicationContext context, MergedContextConfiguration mergedConfig) {

	ModuleTestExecution testExecution = execution.get();

	logModules(testExecution);

	ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
	beanFactory.registerSingleton(BEAN_NAME, testExecution);

	DefaultPublishedEvents events = new DefaultPublishedEvents();
	beanFactory.registerSingleton(events.getClass().getName(), events);
	context.addApplicationListener(events);
}
 
Example 6
public static void main(String[] args) {
    // 创建 ConfigurableApplicationContext 实例 GenericApplicationContext
    ConfigurableApplicationContext context = new GenericApplicationContext();
    System.out.println("创建 Spring 应用上下文 : " + context.getDisplayName());
    // 添加 ApplicationListener 非泛型实现
    context.addApplicationListener(event ->
            System.out.println(event.getClass().getSimpleName())
    );

    // refresh() : 初始化应用上下文
    System.out.println("应用上下文准备初始化...");
    context.refresh(); // 发布 ContextRefreshedEvent
    System.out.println("应用上下文已初始化...");

    // stop() : 停止应用上下文
    System.out.println("应用上下文准备停止启动...");
    context.stop();    // 发布 ContextStoppedEvent
    System.out.println("应用上下文已停止启动...");

    // start(): 启动应用上下文
    System.out.println("应用上下文准备启动启动...");
    context.start();  // 发布 ContextStartedEvent
    System.out.println("应用上下文已启动启动...");

    // close() : 关闭应用上下文
    System.out.println("应用上下文准备关闭...");
    context.close();  // 发布 ContextClosedEvent
    System.out.println("应用上下文已关闭...");

}
 
Example 7
/**
 * 装配SpringContext
 * 设置环境,初始化调用,设置监听器
 */
private void prepareContext(ConfigurableApplicationContext context, ConfigurableEnvironment environment) {
    context.setEnvironment(environment);
    applyInitializer(context);
    for (ApplicationListener listener : listeners) {
        context.addApplicationListener(listener);
    }
}
 
Example 8
Source Project: java-trader   File: ServiceStartAction.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public int execute(BeansContainer beansContainer, PrintWriter writer, List<KVPair> options) throws Exception {
    //解析参数
    init(options);
    ExchangeableTradingTimes tradingTimes = Exchange.SHFE.detectTradingTimes("au", LocalDateTime.now());
    if ( tradingTimes==null ) {
        writer.println(DateUtil.date2str(LocalDateTime.now())+" is not trading time");
        return 1;
    }
    LocalDate tradingDay = null;
    if ( tradingTimes!=null) {
        tradingDay = tradingTimes.getTradingDay();
    }
    long traderPid = getTraderPid();
    if ( traderPid>0 ) {
        writer.println(DateUtil.date2str(LocalDateTime.now())+" Trader process is running: "+traderPid);
        return 1;
    }
    writer.println(DateUtil.date2str(LocalDateTime.now())+" Starting from config "+System.getProperty(TraderHomeUtil.PROP_TRADER_CONFIG_FILE)+", home: " + TraderHomeUtil.getTraderHome()+", trading day: "+tradingDay);
    saveStatusStart();
    List<String> args = new ArrayList<>();
    for(KVPair kv:options) {
        args.add(kv.toString());
    }
    ConfigurableApplicationContext context = SpringApplication.run(appClass, args.toArray(new String[args.size()]));
    saveStatusReady();
    statusFile.deleteOnExit();
    context.addApplicationListener(new ApplicationListener<ContextClosedEvent>() {
        @Override
        public void onApplicationEvent(ContextClosedEvent event) {
            synchronized(statusFile) {
                statusFile.notify();
            }
        }
    });
    synchronized(statusFile) {
        statusFile.wait();
    }
    return 0;
}
 
Example 9
@Override
public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
    final Neo4jContainer<?> neo4jContainer = new Neo4jContainer<>("neo4j:4.0").withoutAuthentication();
    neo4jContainer.start();
    configurableApplicationContext
            .addApplicationListener((ApplicationListener<ContextClosedEvent>) event -> neo4jContainer.stop());
    TestPropertyValues.of("org.neo4j.driver.uri=" + neo4jContainer.getBoltUrl())
            .applyTo(configurableApplicationContext.getEnvironment());
}
 
Example 10
private void publishDiscoveryEvent()
{
    if (this.config == null)
    {
        return;
    }
    final IndexEvent discoveryEvent = new IndexEvent(this, "Discovery", 1);
    final ConfigurableApplicationContext applicationContext = this.config.getApplicationContext();
    try
    {
        applicationContext.publishEvent(discoveryEvent);
    }
    catch (IllegalStateException e)
    {
        // There's a possibility that the application context hasn't fully refreshed yet, so register a listener
        // that will fire when it has
        applicationContext.addApplicationListener(new ApplicationListener()
        {

            public void onApplicationEvent(ApplicationEvent event)
            {
                if (event instanceof ContextRefreshedEvent)
                {
                    applicationContext.publishEvent(discoveryEvent);
                }
            }
        });
    }
}
 
Example 11
static void configureCachingConnectionFactory(
		CachingConnectionFactory connectionFactory,
		ConfigurableApplicationContext applicationContext,
		RabbitProperties rabbitProperties) throws Exception {

	if (StringUtils.hasText(rabbitProperties.getAddresses())) {
		connectionFactory.setAddresses(rabbitProperties.determineAddresses());
	}

	connectionFactory.setPublisherConfirmType(rabbitProperties.getPublisherConfirmType() == null ? ConfirmType.NONE : rabbitProperties.getPublisherConfirmType());
	connectionFactory.setPublisherReturns(rabbitProperties.isPublisherReturns());
	if (rabbitProperties.getCache().getChannel().getSize() != null) {
		connectionFactory.setChannelCacheSize(
				rabbitProperties.getCache().getChannel().getSize());
	}
	if (rabbitProperties.getCache().getConnection().getMode() != null) {
		connectionFactory
				.setCacheMode(rabbitProperties.getCache().getConnection().getMode());
	}
	if (rabbitProperties.getCache().getConnection().getSize() != null) {
		connectionFactory.setConnectionCacheSize(
				rabbitProperties.getCache().getConnection().getSize());
	}
	if (rabbitProperties.getCache().getChannel().getCheckoutTimeout() != null) {
		connectionFactory.setChannelCheckoutTimeout(rabbitProperties.getCache()
				.getChannel().getCheckoutTimeout().toMillis());
	}
	connectionFactory.setApplicationContext(applicationContext);
	applicationContext.addApplicationListener(connectionFactory);
	connectionFactory.afterPropertiesSet();
}
 
Example 12
@Test
public void testBadUserDeclarationsFatal() throws Exception {
	RabbitTestBinder binder = getBinder();
	ConfigurableApplicationContext context = binder.getApplicationContext();
	ConfigurableListableBeanFactory bf = context.getBeanFactory();
	bf.registerSingleton("testBadUserDeclarationsFatal",
			new Queue("testBadUserDeclarationsFatal", false));
	bf.registerSingleton("binder", binder);
	RabbitExchangeQueueProvisioner provisioner = TestUtils.getPropertyValue(binder,
			"binder.provisioningProvider", RabbitExchangeQueueProvisioner.class);
	bf.initializeBean(provisioner, "provisioner");
	bf.registerSingleton("provisioner", provisioner);
	context.addApplicationListener(provisioner);
	RabbitAdmin admin = new RabbitAdmin(rabbitAvailableRule.getResource());
	admin.declareQueue(new Queue("testBadUserDeclarationsFatal"));
	// reset the connection and configure the "user" admin to auto declare queues...
	rabbitAvailableRule.getResource().resetConnection();
	bf.initializeBean(admin, "rabbitAdmin");
	bf.registerSingleton("rabbitAdmin", admin);
	admin.afterPropertiesSet();
	// the mis-configured queue should be fatal
	Binding<?> binding = null;
	try {
		binding = binder.bindConsumer("input", "baddecls",
				this.createBindableChannel("input", new BindingProperties()),
				createConsumerProperties());
		fail("Expected exception");
	}
	catch (BinderException e) {
		assertThat(e.getCause()).isInstanceOf(AmqpIOException.class);
	}
	finally {
		admin.deleteQueue("testBadUserDeclarationsFatal");
		if (binding != null) {
			binding.unbind();
		}
	}
}
 
Example 13
@Autowired
public LineMessageHandlerSupport(
        final ReplyByReturnValueConsumer.Factory returnValueConsumerFactory,
        final ConfigurableApplicationContext applicationContext) {
    this.returnValueConsumerFactory = returnValueConsumerFactory;
    this.applicationContext = applicationContext;

    applicationContext.addApplicationListener(event -> {
        if (event instanceof ContextRefreshedEvent) {
            refresh();
        }
    });
}
 
Example 14
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    // register a context close handler
    if (applicationContext instanceof ConfigurableApplicationContext) {
        ConfigurableApplicationContext context = (ConfigurableApplicationContext) applicationContext;
        context.addApplicationListener(new ApplicationListener<ContextClosedEvent>() {
            @Override
            public void onApplicationEvent(ContextClosedEvent e) {
                LOG.info("Context '" + e.getApplicationContext().getDisplayName() +
                        "' closed, shutting down URLMonitor scheduler");
                dictionaryUrlMonitor.shutdownScheduler();
            }
        });
    }
}
 
Example 15
@Override
    public void initialize(ConfigurableApplicationContext applicationContext) {
//        dubbo源码解析之服务注册
        applicationContext.addApplicationListener(new DubboApplicationListener());
    }
 
Example 16
public ConsulSecretRebindListener(ConfigurationPropertiesRebinder rebinder,
		ConfigurableApplicationContext context) {
	this.rebinder = rebinder;
	context.addApplicationListener(this);
}
 
Example 17
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
  applicationContext.addApplicationListener((ApplicationListener<NettyServerStartingEvent>)
      NettyServerPortInfoApplicaitonInitializer.this::onApplicationEvent);
}
 
Example 18
Source Project: hawkbit   File: EventVerifier.java    License: Eclipse Public License 1.0 4 votes vote down vote up
private void beforeTest(final TestContext testContext) {
    final ConfigurableApplicationContext context = (ConfigurableApplicationContext) testContext
            .getApplicationContext();
    eventCaptor = new EventCaptor();
    context.addApplicationListener(eventCaptor);
}
 
Example 19
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
    applicationContext.addApplicationListener((ApplicationListener<WebServerInitializedEvent>) event -> {
        Testcontainers.exposeHostPorts(event.getWebServer().getPort());
    });
}
 
Example 20
/**
 * The UI scoped event push strategy. Session scope is necessary, that every
 * UI has an own strategy.
 * 
 * @param applicationContext
 *            the context to add the listener to
 * @param executorService
 *            the general scheduler service
 * @param eventBus
 *            the ui event bus
 * @param eventProvider
 *            the event provider
 * @param uiProperties
 *            the ui properties
 * @return the push strategy bean
 */
@Bean
@ConditionalOnMissingBean
@UIScope
EventPushStrategy eventPushStrategy(final ConfigurableApplicationContext applicationContext,
        final ScheduledExecutorService executorService, final UIEventBus eventBus,
        final UIEventProvider eventProvider, final UiProperties uiProperties) {
    final DelayedEventBusPushStrategy delayedEventBusPushStrategy = new DelayedEventBusPushStrategy(executorService,
            eventBus, eventProvider, uiProperties.getEvent().getPush().getDelay());
    applicationContext.addApplicationListener(delayedEventBusPushStrategy);
    return delayedEventBusPushStrategy;
}