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

The following examples show how to use org.springframework.context.ConfigurableApplicationContext#close() . 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: JmsListenerAnnotationBeanPostProcessorTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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
Source File: DefaultEndpointLocatorConfigurationTest.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
@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 3
Source File: LegacySystemEnvironmentBehaviorBootstrap.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 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();
}
 
Example 4
Source File: S1pKafkaApplication.java    From grussell-spring-kafka with Apache License 2.0 5 votes vote down vote up
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
Source File: KafkaBinderJaasInitializerListenerTest.java    From spring-cloud-stream-binder-kafka with Apache License 2.0 5 votes vote down vote up
@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.cloud.stream.kafka.binder.jaas.options.principal=kafka-client-1@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 6
Source File: AnnotationNamespaceDrivenTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@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 7
Source File: EnableJmsTests.java    From java-technology-stack with 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 8
Source File: StreamListenerHandlerMethodTests.java    From spring-cloud-stream with Apache License 2.0 5 votes vote down vote up
@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 9
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 10
Source File: MyApplication.java    From Ratel with 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 11
Source File: RatelTestContext.java    From Ratel with 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 12
Source File: ZipkinRestTemplateSenderConfigurationTest.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
@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 13
Source File: AnnotationLazyInitMBeanTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@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 14
Source File: AsyncAnnotationBeanPostProcessorTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void proxyCreated() {
	ConfigurableApplicationContext context = initContext(
			new RootBeanDefinition(AsyncAnnotationBeanPostProcessor.class));
	Object target = context.getBean("target");
	assertTrue(AopUtils.isAopProxy(target));
	context.close();
}
 
Example 15
Source File: DefaultEndpointLocatorConfigurationTest.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
@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 16
Source File: KafkastreamsBinderPojoInputStringOutputIntegrationTests.java    From spring-cloud-stream-binder-kafka with Apache License 2.0 5 votes vote down vote up
@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 17
Source File: EnableCachingTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@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 18
Source File: IntrospectBizEndpointOnArkDisabledTest.java    From sofa-ark with Apache License 2.0 5 votes vote down vote up
@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 19
Source File: S1pKafkaApplication.java    From grussell-spring-kafka with Apache License 2.0 5 votes vote down vote up
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
Source File: S1pKafkaApplication.java    From grussell-spring-kafka with Apache License 2.0 5 votes vote down vote up
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();
}