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

The following examples show how to use org.springframework.context.ConfigurableApplicationContext#close() . 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
@Test
public void simpleMessageListener() throws Exception {
	ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(
			Config.class, SimpleMessageListenerTestBean.class);

	JmsListenerContainerTestFactory factory = context.getBean(JmsListenerContainerTestFactory.class);
	assertEquals("One container should have been registered", 1, factory.getListenerContainers().size());
	MessageListenerTestContainer container = factory.getListenerContainers().get(0);

	JmsListenerEndpoint endpoint = container.getEndpoint();
	assertEquals("Wrong endpoint type", MethodJmsListenerEndpoint.class, endpoint.getClass());
	MethodJmsListenerEndpoint methodEndpoint = (MethodJmsListenerEndpoint) endpoint;
	assertEquals(SimpleMessageListenerTestBean.class, methodEndpoint.getBean().getClass());
	assertEquals(SimpleMessageListenerTestBean.class.getMethod("handleIt", String.class), methodEndpoint.getMethod());
	assertEquals(SimpleMessageListenerTestBean.class.getMethod("handleIt", String.class), methodEndpoint.getMostSpecificMethod());

	SimpleMessageListenerContainer listenerContainer = new SimpleMessageListenerContainer();
	methodEndpoint.setupListenerContainer(listenerContainer);
	assertNotNull(listenerContainer.getMessageListener());

	assertTrue("Should have been started " + container, container.isStarted());
	context.close(); // Close and stop the listeners
	assertTrue("Should have been stopped " + container, container.isStopped());
}
 
Example 2
@Test
public void enableZipkinDiscoveryClient() {
	ConfigurableApplicationContext ctxt = new SpringApplication(
			ZipkinRestTemplateSenderConfigurationTest.MyDiscoveryClientZipkinUrlExtractorConfiguration.class,
			ZipkinProperties.class)
					.run("--spring.zipkin.discovery-client-enabled=true");
	assertThat(ctxt.getBean(ZipkinLoadBalancer.class))
			.isInstanceOf(LoadBalancerClientZipkinLoadBalancer.class);
	ctxt.close();
}
 
Example 3
public static void main(String[] args) throws Exception {
	ConfigurableApplicationContext context = new SpringApplicationBuilder(S1pKafkaApplication.class)
		.web(false)
		.run(args);
	TestBean testBean = context.getBean(TestBean.class);
	testBean.send(new Foo("foo", "bar"));
	context.getBean(Listener.class).latch.await(60, TimeUnit.SECONDS);
	context.close();
}
 
Example 4
public static void main(String[] args) throws Exception {
	ConfigurableApplicationContext context = new SpringApplicationBuilder(S1pKafkaApplication.class)
		.web(false)
		.run(args);
	TestBean testBean = context.getBean(TestBean.class);
	testBean.send("foo");
	context.getBean(Listener.class).latch.await(60, TimeUnit.SECONDS);
	context.close();
}
 
Example 5
@Test
public void testIntrospectBizEndpoint() {
    SpringApplication springApplication = new SpringApplication(EmptyConfiguration.class);
    ConfigurableApplicationContext applicationContext = springApplication.run(new String[] {});
    Assert.assertFalse(applicationContext.containsBean("introspectBizEndpoint"));
    Assert.assertFalse(applicationContext.containsBean("introspectBizEndpointMvcAdapter"));
    applicationContext.close();
}
 
Example 6
@Test
public void emptyConfigSupport() {
	ConfigurableApplicationContext context =
			new AnnotationConfigApplicationContext(EmptyConfigSupportConfig.class);

	CacheInterceptor ci = context.getBean(CacheInterceptor.class);
	assertNotNull(ci.getCacheResolver());
	assertEquals(SimpleCacheResolver.class, ci.getCacheResolver().getClass());
	assertSame(context.getBean(CacheManager.class),
			((SimpleCacheResolver)ci.getCacheResolver()).getCacheManager());
	context.close();
}
 
Example 7
@Test
public void testKstreamBinderWithPojoInputAndStringOuput() throws Exception {
	SpringApplication app = new SpringApplication(ProductCountApplication.class);
	app.setWebApplicationType(WebApplicationType.NONE);
	ConfigurableApplicationContext context = app.run("--server.port=0",
			"--spring.jmx.enabled=false",
			"--spring.cloud.stream.bindings.input.destination=foos",
			"--spring.cloud.stream.bindings.output.destination=counts-id",
			"--spring.cloud.stream.kafka.streams.binder.configuration.commit.interval.ms=1000",
			"--spring.cloud.stream.kafka.streams.binder.configuration.default.key.serde"
					+ "=org.apache.kafka.common.serialization.Serdes$StringSerde",
			"--spring.cloud.stream.kafka.streams.binder.configuration.default.value.serde"
					+ "=org.apache.kafka.common.serialization.Serdes$StringSerde",
			"--spring.cloud.stream.kafka.streams.bindings.input.consumer.applicationId=ProductCountApplication-xyz",
			"--spring.cloud.stream.kafka.streams.binder.brokers="
					+ embeddedKafka.getBrokersAsString());
	try {
		receiveAndValidateFoo();
		// Assertions on StreamBuilderFactoryBean
		StreamsBuilderFactoryBean streamsBuilderFactoryBean = context
				.getBean("&stream-builder-ProductCountApplication-process", StreamsBuilderFactoryBean.class);
		CleanupConfig cleanup = TestUtils.getPropertyValue(streamsBuilderFactoryBean,
				"cleanupConfig", CleanupConfig.class);
		assertThat(cleanup.cleanupOnStart()).isFalse();
		assertThat(cleanup.cleanupOnStop()).isTrue();
	}
	finally {
		context.close();
	}
}
 
Example 8
@Test
public void endpointLocatorShouldDefaultToServerPropertiesEndpointLocatorEvenWhenDiscoveryClientPresent() {
	ConfigurableApplicationContext ctxt = new SpringApplication(
			ConfigurationWithRegistration.class).run("--spring.jmx.enabled=false");
	assertThat(ctxt.getBean(EndpointLocator.class))
			.isInstanceOf(DefaultEndpointLocator.class);
	ctxt.close();
}
 
Example 9
@Test
public void proxyCreated() {
	ConfigurableApplicationContext context = initContext(
			new RootBeanDefinition(AsyncAnnotationBeanPostProcessor.class));
	Object target = context.getBean("target");
	assertTrue(AopUtils.isAopProxy(target));
	context.close();
}
 
Example 10
@Test
public void lazyNaming() throws Exception {
	ConfigurableApplicationContext ctx =
			new ClassPathXmlApplicationContext("org/springframework/jmx/export/annotation/lazyNaming.xml");
	try {
		MBeanServer server = (MBeanServer) ctx.getBean("server");
		ObjectName oname = ObjectNameManager.getInstance("bean:name=testBean4");
		assertNotNull(server.getObjectInstance(oname));
		String name = (String) server.getAttribute(oname, "Name");
		assertEquals("Invalid name returned", "TEST", name);
	}
	finally {
		ctx.close();
	}
}
 
Example 11
@Test
public void endpointLocatorShouldDefaultToServerPropertiesEndpointLocator() {
	ConfigurableApplicationContext ctxt = new SpringApplication(
			EmptyConfiguration.class).run("--spring.jmx.enabled=false");
	assertThat(ctxt.getBean(EndpointLocator.class))
			.isInstanceOf(DefaultEndpointLocator.class);
	ctxt.close();
}
 
Example 12
Source Project: Ratel   File: RatelTestContext.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Closes all spring contexts that were created in.
 */
public void close() {
  for (ConfigurableApplicationContext ctx : myContexts) {
    ctx.close();
  }
  firstFreePort = FREE_PORTS_START;
  serviceDiscoveryPort++;
  myContexts.clear();
  observedContexts.clear();
}
 
Example 13
Source Project: Ratel   File: MyApplication.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    SpringApplication app = new SpringApplication(MyApplication.class);
    app.setWebEnvironment(false);
    ConfigurableApplicationContext ctx = app.run(args);

    MyApplication myApp = ctx.getBean(MyApplication.class);
    myApp.playConsoleGame();

    ctx.close();
}
 
Example 14
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 15
@Test
public void testMethodWithMultipleInputParameters() throws Exception {
	ConfigurableApplicationContext context = SpringApplication.run(
			TestMethodWithMultipleInputParameters.class, "--server.port=0",
			"--spring.jmx.enabled=false");
	Processor processor = context.getBean(Processor.class);
	StreamListenerTestUtils.FooInboundChannel1 inboundChannel2 = context
			.getBean(StreamListenerTestUtils.FooInboundChannel1.class);
	final CountDownLatch latch = new CountDownLatch(2);
	((SubscribableChannel) processor.output()).subscribe(new MessageHandler() {
		@Override
		public void handleMessage(Message<?> message) throws MessagingException {
			Assert.isTrue(
					message.getPayload().equals("footesting")
							|| message.getPayload().equals("BARTESTING"),
					"Assert failed");
			latch.countDown();
		}
	});
	processor.input().send(MessageBuilder.withPayload("{\"foo\":\"fooTESTing\"}")
			.setHeader("contentType", "application/json").build());
	inboundChannel2.input()
			.send(MessageBuilder.withPayload("{\"bar\":\"bartestING\"}")
					.setHeader("contentType", "application/json").build());
	assertThat(latch.await(1, TimeUnit.SECONDS));
	context.close();
}
 
Example 16
Source Project: java-technology-stack   File: EnableJmsTests.java    License: MIT License 5 votes vote down vote up
@Test
public void lazyComponent() {
	ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(
			EnableJmsDefaultContainerFactoryConfig.class, LazyBean.class);
	JmsListenerContainerTestFactory defaultFactory =
			context.getBean("jmsListenerContainerFactory", JmsListenerContainerTestFactory.class);
	assertEquals(0, defaultFactory.getListenerContainers().size());

	context.getBean(LazyBean.class);  // trigger lazy resolution
	assertEquals(1, defaultFactory.getListenerContainers().size());
	MessageListenerTestContainer container = defaultFactory.getListenerContainers().get(0);
	assertTrue("Should have been started " + container, container.isStarted());
	context.close();  // close and stop the listeners
	assertTrue("Should have been stopped " + container, container.isStopped());
}
 
Example 17
@Test
public void bothSetOnlyResolverIsUsed() {
	ConfigurableApplicationContext context = new GenericXmlApplicationContext(
			"/org/springframework/cache/config/annotationDrivenCacheNamespace-manager-resolver.xml");

	CacheInterceptor ci = context.getBean(CacheInterceptor.class);
	assertSame(context.getBean("cacheResolver"), ci.getCacheResolver());
	context.close();
}
 
Example 18
@Test
@Ignore("CI randomly fails this test, need to investigate further. ")
public void testConfigurationParsedCorrectlyWithKafkaClientAndDefaultControlFlag()
		throws Exception {
	ConfigFile configFile = new ConfigFile(
			new ClassPathResource("jaas-sample-kafka-only.conf").getURI());
	final AppConfigurationEntry[] kafkaConfigurationArray = configFile
			.getAppConfigurationEntry("KafkaClient");

	final ConfigurableApplicationContext context = SpringApplication.run(
			SimpleApplication.class,
			"--spring.cloud.stream.kafka.binder.jaas.options.useKeyTab=true",
			"--spring.cloud.stream.kafka.binder.jaas.options.storeKey=true",
			"--spring.cloud.stream.kafka.binder.jaas.options.keyTab=/etc/security/keytabs/kafka_client.keytab",
			"--spring.[email protected]EXAMPLE.COM",
			"--spring.jmx.enabled=false");
	javax.security.auth.login.Configuration configuration = javax.security.auth.login.Configuration
			.getConfiguration();

	final AppConfigurationEntry[] kafkaConfiguration = configuration
			.getAppConfigurationEntry("KafkaClient");
	assertThat(kafkaConfiguration).hasSize(1);
	assertThat(kafkaConfiguration[0].getOptions())
			.isEqualTo(kafkaConfigurationArray[0].getOptions());
	assertThat(kafkaConfiguration[0].getControlFlag())
			.isEqualTo(AppConfigurationEntry.LoginModuleControlFlag.REQUIRED);
	context.close();
}
 
Example 19
public static void main(String[] args) throws Exception {
	ConfigurableApplicationContext context = new SpringApplicationBuilder(S1pKafkaApplication.class)
		.web(false)
		.run(args);
	TestBean testBean = context.getBean(TestBean.class);
	testBean.send("foo");
	context.getBean(Listener.class).latch.await(60, TimeUnit.SECONDS);
	context.close();
}
 
Example 20
public static void main(String[] args) {
    ConfigurableApplicationContext context =
            new SpringApplicationBuilder(
                    LegacySystemEnvironmentBehaviorBootstrap.class, User.class)
                    .web(false) // 非 Web 应用
                    .properties("user.id = 1") // 设置默认属性(最低外部化配置优先级)
                    .run(args);
    User user = context.getBean(User.class);
    System.out.println("user 用户对象 : " + user);
    context.close();
}