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

The following examples show how to use org.springframework.context.annotation.AnnotationConfigApplicationContext#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
Source Project: spring-analysis-note   File: EnableAsyncTests.java    License: MIT License 6 votes vote down vote up
@Test
public void withAsyncBeanWithExecutorQualifiedByName() throws ExecutionException, InterruptedException {
	AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
	ctx.register(AsyncWithExecutorQualifiedByNameConfig.class);
	ctx.refresh();

	AsyncBeanWithExecutorQualifiedByName asyncBean = ctx.getBean(AsyncBeanWithExecutorQualifiedByName.class);
	Future<Thread> workerThread0 = asyncBean.work0();
	assertThat(workerThread0.get().getName(), not(anyOf(startsWith("e1-"), startsWith("otherExecutor-"))));
	Future<Thread> workerThread = asyncBean.work();
	assertThat(workerThread.get().getName(), startsWith("e1-"));
	Future<Thread> workerThread2 = asyncBean.work2();
	assertThat(workerThread2.get().getName(), startsWith("otherExecutor-"));
	Future<Thread> workerThread3 = asyncBean.work3();
	assertThat(workerThread3.get().getName(), startsWith("otherExecutor-"));

	ctx.close();
}
 
Example 2
@Test
public void spr11915() {
	AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(Spr11915Config.class);
	TransactionalTestBean bean = ctx.getBean(TransactionalTestBean.class);
	CallCountingTransactionManager txManager = ctx.getBean("qualifiedTransactionManager", CallCountingTransactionManager.class);

	bean.saveQualifiedFoo();
	assertThat(txManager.begun, equalTo(1));
	assertThat(txManager.commits, equalTo(1));
	assertThat(txManager.rollbacks, equalTo(0));

	bean.saveQualifiedFooWithAttributeAlias();
	assertThat(txManager.begun, equalTo(2));
	assertThat(txManager.commits, equalTo(2));
	assertThat(txManager.rollbacks, equalTo(0));

	ctx.close();
}
 
Example 3
Source Project: spring-analysis-note   File: EnableAsyncTests.java    License: MIT License 6 votes vote down vote up
@Test
public void customExecutorBean() {
	// Arrange
	AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
	ctx.register(CustomExecutorBean.class);
	ctx.refresh();
	AsyncBean asyncBean = ctx.getBean(AsyncBean.class);
	// Act
	asyncBean.work();
	// Assert
	Awaitility.await()
				.atMost(500, TimeUnit.MILLISECONDS)
				.pollInterval(10, TimeUnit.MILLISECONDS)
				.until(() -> asyncBean.getThreadOfExecution() != null);
	assertThat(asyncBean.getThreadOfExecution().getName(), startsWith("Custom-"));
	ctx.close();
}
 
Example 4
public static void main(String[] args) {
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
    // 注册当前 Class
    context.register(SpringMBeanServerBeanBootstrap.class);
    // 启动应用上下文
    context.refresh();
    // 获取名为 "mBeanExporter" Bean,来自于 mBeanExporter() 方法 @Bean 定义
    MBeanExporter mBeanExporter = context.getBean("mBeanExporter", MBeanExporter.class);
    // 获取名为 "mBeanServer" Bean,来自于 mBeanServer() 方法 @Bean 定义
    MBeanServer mBeanServer = context.getBean("mBeanServer", MBeanServer.class);
    // 从 "mBeanExporter" Bean 中获取来自于其afterPropertiesSet()方法创建 "mBeanServer" 对象
    MBeanServer mBeanServerFromMBeanExporter = mBeanExporter.getServer();
    System.out.printf("来自 mBeanExporter Bean 关联的 MBeanServer 实例是否等于平台 MBeanServer : %b \n",
            mBeanServerFromMBeanExporter == ManagementFactory.getPlatformMBeanServer()
    );

    System.out.printf("来自 mBeanExporter Bean 关联的 MBeanServer 实例是否等于 mBeanServer Bean : %b \n",
            mBeanServerFromMBeanExporter == mBeanServer
    );
    // 关闭应用上下文
    context.close();
}
 
Example 5
public static void main(String[] args) {
    // 1. 创建 parent Spring 应用上下文
    AnnotationConfigApplicationContext parentContext = new AnnotationConfigApplicationContext();
    parentContext.setId("parent-context");
    // 注册 MyListener 到 parent Spring 应用上下文
    parentContext.register(MyListener.class);

    // 2. 创建 current Spring 应用上下文
    AnnotationConfigApplicationContext currentContext = new AnnotationConfigApplicationContext();
    currentContext.setId("current-context");
    // 3. current -> parent
    currentContext.setParent(parentContext);
    // 注册 MyListener 到 current Spring 应用上下文
    currentContext.register(MyListener.class);

    // 4.启动 parent Spring 应用上下文
    parentContext.refresh();

    // 5.启动 current Spring 应用上下文
    currentContext.refresh();

    // 关闭所有 Spring 应用上下文
    currentContext.close();
    parentContext.close();
}
 
Example 6
public static void main(String[] args) {
    // 创建 BeanFactory 容器
    AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
    // 将当前类 ObjectProviderDemo 作为配置类(Configuration Class)
    applicationContext.register(ObjectProviderDemo.class);
    // 启动应用上下文
    applicationContext.refresh();
    // 依赖查找集合对象
    lookupByObjectProvider(applicationContext);
    lookupIfAvailable(applicationContext);
    lookupByStreamOps(applicationContext);

    // 关闭应用上下文
    applicationContext.close();

}
 
Example 7
@Test
public void ttlCanBeCustomized() {
	AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
	EnvironmentTestUtils.addEnvironment(context, "cassandra.ttl:" + 1000);
	context.register(Conf.class);
	context.refresh();
	CassandraSinkProperties properties = context.getBean(CassandraSinkProperties.class);
	assertThat(properties.getTtl(), equalTo(1000));
	context.close();
}
 
Example 8
public static void main(String[] args) throws IOException {
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
    // 注册 SpringJmxAnnotationBootstrap
    context.register(SpringJmxAnnotationBootstrap.class);
    // 启动应用上下文
    context.refresh();
    System.out.println("按任意键结束...");
    System.in.read();
    // 关闭应用上下文
    context.close();
}
 
Example 9
Source Project: journaldev   File: MySpringApp.java    License: MIT License 5 votes vote down vote up
public static void main(String[] args) {
	AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
	ctx.register(MyConfiguration.class);
	ctx.refresh();

	MyBean mb1 = ctx.getBean(MyBean.class);
	System.out.println(mb1.hashCode());

	MyBean mb2 = ctx.getBean(MyBean.class);
	System.out.println(mb2.hashCode());

	ctx.close();
}
 
Example 10
@Test
public void ingestQueryCanBeCustomized() {
	String query = "insert into book (isbn, title, author) values (?, ?, ?)";
	AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
	EnvironmentTestUtils.addEnvironment(context, "cassandra.ingest-query:" + query);
	context.register(Conf.class);
	context.refresh();
	CassandraSinkProperties properties = context.getBean(CassandraSinkProperties.class);
	assertThat(properties.getIngestQuery(), equalTo(query));
	context.close();
}
 
Example 11
@Ignore // TODO: SPR-6310
@Test
public void importXmlByConvention() {
	AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(
		ImportXmlByConventionConfig.class);
	assertTrue("context does not contain xml-declared bean", ctx.containsBean("xmlDeclaredBean"));
	ctx.close();
}
 
Example 12
public static void main(String[] args) {
    // 创建 BeanFactory 容器
    AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();

    // 注册 BeanDefinition Bean Class 是一个 CharSequence 接口
    BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(CharSequence.class);
    applicationContext.registerBeanDefinition("errorBean", beanDefinitionBuilder.getBeanDefinition());

    // 启动应用上下文
    applicationContext.refresh();

    // 关闭应用上下文
    applicationContext.close();
}
 
Example 13
@Test
public void transactionalEventListenerRegisteredProperly() {
	AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(EnableTxConfig.class);
	assertTrue(ctx.containsBean(TransactionManagementConfigUtils.TRANSACTIONAL_EVENT_LISTENER_FACTORY_BEAN_NAME));
	assertEquals(1, ctx.getBeansOfType(TransactionalEventListenerFactory.class).size());
	ctx.close();
}
 
Example 14
@Test
public void txManagerIsResolvedCorrectlyWhenMultipleManagersArePresent() {
	AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(
			EnableTxConfig.class, MultiTxManagerConfig.class);
	TransactionalTestBean bean = ctx.getBean(TransactionalTestBean.class);

	// invoke a transactional method, causing the PlatformTransactionManager bean to be resolved.
	bean.findAllFoos();
	ctx.close();
}
 
Example 15
Source Project: tutorials   File: TenantScopeIntegrationTest.java    License: MIT License 5 votes vote down vote up
@Test
public final void whenRegisterScopeAndBeans_thenContextContainsFooAndBar() {
    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
    try {
        ctx.register(TenantScopeConfig.class);
        ctx.register(TenantBeansConfig.class);
        ctx.refresh();

        TenantBean foo = (TenantBean) ctx.getBean("foo", TenantBean.class);
        foo.sayHello();
        TenantBean bar = (TenantBean) ctx.getBean("bar", TenantBean.class);
        bar.sayHello();
        Map<String, TenantBean> foos = ctx.getBeansOfType(TenantBean.class);

        assertThat(foo, not(equalTo(bar)));
        assertThat(foos.size(), equalTo(2));
        assertTrue(foos.containsValue(foo));
        assertTrue(foos.containsValue(bar));

        BeanDefinition fooDefinition = ctx.getBeanDefinition("foo");
        BeanDefinition barDefinition = ctx.getBeanDefinition("bar");

        assertThat(fooDefinition.getScope(), equalTo("tenant"));
        assertThat(barDefinition.getScope(), equalTo("tenant"));
    } finally {
        ctx.close();
    }
}
 
Example 16
@Test
public void configurationWithAdaptiveResourcePrototypes() {
	AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
	ctx.register(ConfigWithPrototypeBean.class, AdaptiveResourceInjectionPoints.class);
	ctx.refresh();

	AdaptiveResourceInjectionPoints adaptive = ctx.getBean(AdaptiveResourceInjectionPoints.class);
	assertEquals("adaptiveInjectionPoint1", adaptive.adaptiveInjectionPoint1.getName());
	assertEquals("setAdaptiveInjectionPoint2", adaptive.adaptiveInjectionPoint2.getName());

	adaptive = ctx.getBean(AdaptiveResourceInjectionPoints.class);
	assertEquals("adaptiveInjectionPoint1", adaptive.adaptiveInjectionPoint1.getName());
	assertEquals("setAdaptiveInjectionPoint2", adaptive.adaptiveInjectionPoint2.getName());
	ctx.close();
}
 
Example 17
public static void main(String[] args) {
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
    // 注册 Configuration Class
    context.register(ObjectFactoryLazyLookupDemo.class);

    // 启动 Spring 应用上下文
    context.refresh();

    ObjectFactoryLazyLookupDemo objectFactoryLazyLookupDemo = context.getBean(ObjectFactoryLazyLookupDemo.class);

    // userObjectFactory userObjectProvider;

    // 代理对象
    ObjectFactory<User> userObjectFactory = objectFactoryLazyLookupDemo.userObjectFactory;
    ObjectFactory<User> userObjectProvider = objectFactoryLazyLookupDemo.userObjectProvider;

    System.out.println("userObjectFactory == userObjectProvider : " +
            (userObjectFactory == userObjectProvider));

    System.out.println("userObjectFactory.getClass() == userObjectProvider.getClass() : " +
            (userObjectFactory.getClass() == userObjectProvider.getClass()));

    // 实际对象(延迟查找)
    System.out.println("user = " + userObjectFactory.getObject());
    System.out.println("user = " + userObjectProvider.getObject());
    System.out.println("user = " + context.getBean(User.class));


    // 关闭 Spring 应用上下文
    context.close();
}
 
Example 18
Source Project: jigsaw-payment   File: HelloServer.java    License: Apache License 2.0 4 votes vote down vote up
public static void main(String[] args){
	AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(HelloServerConfig.class);
	context.close();
}
 
Example 19
Source Project: spring4.x-project   File: Main.java    License: Apache License 2.0 3 votes vote down vote up
public static void main(String[] args) {
	 AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ElConfig.class);
	 
	 ElConfig resourceService = context.getBean(ElConfig.class);
	 
	 resourceService.outputResource();
	 
	 context.close();
}
 
Example 20
@Test
void exposesEventPublicationForFailedListener() {

	AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
	context.register(ApplicationConfiguration.class, InfrastructureConfiguration.class);
	context.refresh();

	Method method = ReflectionUtils.findMethod(SecondTxEventListener.class, "on", DomainEvent.class);

	try {

		context.getBean(Client.class).method();

	} catch (Throwable e) {

		System.out.println(e);

	} finally {

		Iterable<EventPublication> eventsToBePublished = context.getBean(EventPublicationRegistry.class)
				.findIncompletePublications();

		assertThat(eventsToBePublished).hasSize(1);
		assertThat(eventsToBePublished).allSatisfy(it -> {
			assertThat(it.getTargetIdentifier()).isEqualTo(PublicationTargetIdentifier.forMethod(method));
		});

		context.close();
	}
}