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

The following examples show how to use org.springframework.context.ConfigurableApplicationContext#addApplicationListener() . 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: ApplicationThreadLocalCleaner.java    From rice with Educational Community License v2.0 6 votes vote down vote up
@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 File: WireMockInitializer.java    From blog-tutorials with 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 File: IndexInfo.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
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 4
Source File: ReloadingDataDictionary.java    From rice with Educational Community License v2.0 5 votes vote down vote up
@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 5
Source File: LineMessageHandlerSupport.java    From line-bot-sdk-java with Apache License 2.0 5 votes vote down vote up
@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 6
Source File: RabbitBinderTests.java    From spring-cloud-stream-binder-rabbit with Apache License 2.0 5 votes vote down vote up
@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 7
Source File: RabbitServiceAutoConfiguration.java    From spring-cloud-stream-binder-rabbit with Apache License 2.0 5 votes vote down vote up
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 8
Source File: PostRepositoryTest.java    From spring-reactive-sample with GNU General Public License v3.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 9
Source File: ServiceStartAction.java    From java-trader with 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 10
Source File: NetstrapBootApplication.java    From netstrap with Apache License 2.0 5 votes vote down vote up
/**
 * 装配SpringContext
 * 设置环境,初始化调用,设置监听器
 */
private void prepareContext(ConfigurableApplicationContext context, ConfigurableEnvironment environment) {
    context.setEnvironment(environment);
    applyInitializer(context);
    for (ApplicationListener listener : listeners) {
        context.addApplicationListener(listener);
    }
}
 
Example 11
Source File: ApplicationListenerOnSpringEventsBootstrap.java    From thinking-in-spring-boot-samples with Apache License 2.0 5 votes vote down vote up
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 12
Source File: ModuleContextCustomizerFactory.java    From moduliths with Apache License 2.0 5 votes vote down vote up
@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 13
Source File: TestContainerInitializer.java    From sdn-rx with 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 14
Source File: TestContainerInitializer.java    From sdn-rx with 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 15
Source File: DubboApplicationContextInitializer.java    From dubbo-2.6.5 with Apache License 2.0 4 votes vote down vote up
@Override
    public void initialize(ConfigurableApplicationContext applicationContext) {
//        dubbo源码解析之服务注册
        applicationContext.addApplicationListener(new DubboApplicationListener());
    }
 
Example 16
Source File: VaultConfigConsulAutoConfiguration.java    From spring-cloud-vault with Apache License 2.0 4 votes vote down vote up
public ConsulSecretRebindListener(ConfigurationPropertiesRebinder rebinder,
		ConfigurableApplicationContext context) {
	this.rebinder = rebinder;
	context.addApplicationListener(this);
}
 
Example 17
Source File: NettyServerPortInfoApplicaitonInitializer.java    From grpc-spring-boot-starter with MIT License 4 votes vote down vote up
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
  applicationContext.addApplicationListener((ApplicationListener<NettyServerStartingEvent>)
      NettyServerPortInfoApplicaitonInitializer.this::onApplicationEvent);
}
 
Example 18
Source File: EventVerifier.java    From hawkbit with 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
Source File: SeleniumContainerTest.java    From testcontainers-java with MIT License 4 votes vote down vote up
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
    applicationContext.addApplicationListener((ApplicationListener<WebServerInitializedEvent>) event -> {
        Testcontainers.exposeHostPorts(event.getWebServer().getPort());
    });
}
 
Example 20
Source File: MgmtUiAutoConfiguration.java    From hawkbit with Eclipse Public License 1.0 3 votes vote down vote up
/**
 * 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;
}