Java Code Examples for org.springframework.context.support.StaticApplicationContext#refresh()

The following examples show how to use org.springframework.context.support.StaticApplicationContext#refresh() . 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: DispatcherHandlerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void handlerMappingOrder() {
	HandlerMapping hm1 = mock(HandlerMapping.class, withSettings().extraInterfaces(Ordered.class));
	HandlerMapping hm2 = mock(HandlerMapping.class, withSettings().extraInterfaces(Ordered.class));
	when(((Ordered) hm1).getOrder()).thenReturn(1);
	when(((Ordered) hm2).getOrder()).thenReturn(2);
	when((hm1).getHandler(any())).thenReturn(Mono.just((Supplier<String>) () -> "1"));
	when((hm2).getHandler(any())).thenReturn(Mono.just((Supplier<String>) () -> "2"));

	StaticApplicationContext context = new StaticApplicationContext();
	context.registerBean("b2", HandlerMapping.class, () -> hm2);
	context.registerBean("b1", HandlerMapping.class, () -> hm1);
	context.registerBean(HandlerAdapter.class, SupplierHandlerAdapter::new);
	context.registerBean(HandlerResultHandler.class, StringHandlerResultHandler::new);
	context.refresh();

	DispatcherHandler dispatcherHandler = new DispatcherHandler(context);

	MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/"));
	dispatcherHandler.handle(exchange).block(Duration.ofSeconds(0));
	assertEquals("1", exchange.getResponse().getBodyAsString().block(Duration.ofSeconds(5)));
}
 
Example 2
Source File: ApplicationContextEventTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void listenersInApplicationContextWithNestedChild() {
	StaticApplicationContext context = new StaticApplicationContext();
	RootBeanDefinition nestedChild = new RootBeanDefinition(StaticApplicationContext.class);
	nestedChild.getPropertyValues().add("parent", context);
	nestedChild.setInitMethodName("refresh");
	context.registerBeanDefinition("nestedChild", nestedChild);
	RootBeanDefinition listener1Def = new RootBeanDefinition(MyOrderedListener1.class);
	listener1Def.setDependsOn("nestedChild");
	context.registerBeanDefinition("listener1", listener1Def);
	context.refresh();

	MyOrderedListener1 listener1 = context.getBean("listener1", MyOrderedListener1.class);
	MyEvent event1 = new MyEvent(context);
	context.publishEvent(event1);
	assertTrue(listener1.seenEvents.contains(event1));

	SimpleApplicationEventMulticaster multicaster = context.getBean(
			AbstractApplicationContext.APPLICATION_EVENT_MULTICASTER_BEAN_NAME,
			SimpleApplicationEventMulticaster.class);
	assertFalse(multicaster.getApplicationListeners().isEmpty());

	context.close();
	assertTrue(multicaster.getApplicationListeners().isEmpty());
}
 
Example 3
Source File: RqueueMessageHandlerTest.java    From rqueue with Apache License 2.0 6 votes vote down vote up
@Test
public void priorityResolverMultiLevelQueue() {
  StaticApplicationContext applicationContext = new StaticApplicationContext();
  applicationContext.registerSingleton("messageHandler", MessageHandlerWithPriority.class);
  applicationContext.registerSingleton("rqueueMessageHandler", DummyMessageHandler.class);
  Map<String, Object> map = new HashMap<>();
  map.put("queue.name", slowQueue + "," + smartQueue);
  map.put("queue.priority", "critical=10,high=5,low=2");
  applicationContext
      .getEnvironment()
      .getPropertySources()
      .addLast(new MapPropertySource("test", map));
  applicationContext.refresh();
  DummyMessageHandler messageHandler = applicationContext.getBean(DummyMessageHandler.class);
  Map<String, Integer> priority = new HashMap<>();
  priority.put("critical", 10);
  priority.put("high", 5);
  priority.put("low", 2);
  assertEquals(priority, messageHandler.mappingInformation.getPriority());
}
 
Example 4
Source File: AsyncAnnotationBeanPostProcessorTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void taskExecutorByBeanType() {
	StaticApplicationContext context = new StaticApplicationContext();

	BeanDefinition processorDefinition = new RootBeanDefinition(AsyncAnnotationBeanPostProcessor.class);
	context.registerBeanDefinition("postProcessor", processorDefinition);

	BeanDefinition executorDefinition = new RootBeanDefinition(ThreadPoolTaskExecutor.class);
	executorDefinition.getPropertyValues().add("threadNamePrefix", "testExecutor");
	context.registerBeanDefinition("myExecutor", executorDefinition);

	BeanDefinition targetDefinition =
			new RootBeanDefinition(AsyncAnnotationBeanPostProcessorTests.TestBean.class);
	context.registerBeanDefinition("target", targetDefinition);

	context.refresh();

	ITestBean testBean = context.getBean("target", ITestBean.class);
	testBean.test();
	testBean.await(3000);
	Thread asyncThread = testBean.getThread();
	assertTrue(asyncThread.getName().startsWith("testExecutor"));
	context.close();
}
 
Example 5
Source File: AsyncAnnotationBeanPostProcessorTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void taskExecutorByBeanType() {
	StaticApplicationContext context = new StaticApplicationContext();

	BeanDefinition processorDefinition = new RootBeanDefinition(AsyncAnnotationBeanPostProcessor.class);
	context.registerBeanDefinition("postProcessor", processorDefinition);

	BeanDefinition executorDefinition = new RootBeanDefinition(ThreadPoolTaskExecutor.class);
	executorDefinition.getPropertyValues().add("threadNamePrefix", "testExecutor");
	context.registerBeanDefinition("myExecutor", executorDefinition);

	BeanDefinition targetDefinition =
			new RootBeanDefinition(AsyncAnnotationBeanPostProcessorTests.TestBean.class);
	context.registerBeanDefinition("target", targetDefinition);

	context.refresh();

	ITestBean testBean = context.getBean("target", ITestBean.class);
	testBean.test();
	testBean.await(3000);
	Thread asyncThread = testBean.getThread();
	assertTrue(asyncThread.getName().startsWith("testExecutor"));
	context.close();
}
 
Example 6
Source File: QueueMessageHandlerTest.java    From spring-cloud-aws with Apache License 2.0 6 votes vote down vote up
@Test
void receiveMessage_methodAnnotatedWithSqsListenerAnnotation_methodInvokedForIncomingMessage() {
	StaticApplicationContext applicationContext = new StaticApplicationContext();
	applicationContext.registerSingleton("incomingMessageHandler",
			IncomingMessageHandler.class);
	applicationContext.registerSingleton("queueMessageHandler",
			QueueMessageHandler.class);
	applicationContext.refresh();

	MessageHandler messageHandler = applicationContext.getBean(MessageHandler.class);
	messageHandler.handleMessage(MessageBuilder.withPayload("testContent")
			.setHeader(QueueMessageHandler.LOGICAL_RESOURCE_ID, "receive").build());

	IncomingMessageHandler messageListener = applicationContext
			.getBean(IncomingMessageHandler.class);
	assertThat(messageListener.getLastReceivedMessage()).isEqualTo("testContent");
}
 
Example 7
Source File: ApplicationContextEventTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void nonSingletonListenerInApplicationContext() {
	StaticApplicationContext context = new StaticApplicationContext();
	RootBeanDefinition listener = new RootBeanDefinition(MyNonSingletonListener.class);
	listener.setScope(RootBeanDefinition.SCOPE_PROTOTYPE);
	context.registerBeanDefinition("listener", listener);
	context.refresh();

	MyEvent event1 = new MyEvent(context);
	context.publishEvent(event1);
	MyOtherEvent event2 = new MyOtherEvent(context);
	context.publishEvent(event2);
	MyEvent event3 = new MyEvent(context);
	context.publishEvent(event3);
	MyOtherEvent event4 = new MyOtherEvent(context);
	context.publishEvent(event4);
	assertTrue(MyNonSingletonListener.seenEvents.contains(event1));
	assertTrue(MyNonSingletonListener.seenEvents.contains(event2));
	assertTrue(MyNonSingletonListener.seenEvents.contains(event3));
	assertTrue(MyNonSingletonListener.seenEvents.contains(event4));
	MyNonSingletonListener.seenEvents.clear();

	context.close();
}
 
Example 8
Source File: AutoProxyCreatorTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testAutoProxyCreatorWithPackageVisibleMethod() {
	StaticApplicationContext sac = new StaticApplicationContext();
	sac.registerSingleton("testAutoProxyCreator", TestAutoProxyCreator.class);
	sac.registerSingleton("packageVisibleMethodToBeProxied", PackageVisibleMethod.class);
	sac.refresh();

	TestAutoProxyCreator tapc = (TestAutoProxyCreator) sac.getBean("testAutoProxyCreator");
	tapc.testInterceptor.nrOfInvocations = 0;

	PackageVisibleMethod tb = (PackageVisibleMethod) sac.getBean("packageVisibleMethodToBeProxied");
	assertTrue(AopUtils.isCglibProxy(tb));
	assertEquals(0, tapc.testInterceptor.nrOfInvocations);
	tb.doSomething();
	assertEquals(1, tapc.testInterceptor.nrOfInvocations);
}
 
Example 9
Source File: ApplicationContextEventTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void listenerAndBroadcasterWithCircularReference() {
	StaticApplicationContext context = new StaticApplicationContext();
	context.registerBeanDefinition("broadcaster", new RootBeanDefinition(BeanThatBroadcasts.class));
	RootBeanDefinition listenerDef = new RootBeanDefinition(BeanThatListens.class);
	listenerDef.getConstructorArgumentValues().addGenericArgumentValue(new RuntimeBeanReference("broadcaster"));
	context.registerBeanDefinition("listener", listenerDef);
	context.refresh();

	BeanThatBroadcasts broadcaster = context.getBean("broadcaster", BeanThatBroadcasts.class);
	context.publishEvent(new MyEvent(context));
	assertEquals("The event was not received by the listener", 2, broadcaster.receivedCount);

	context.close();
}
 
Example 10
Source File: QuartzSupportTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
@SuppressWarnings("resource")
public void schedulerAutoStartsOnContextRefreshedEventByDefault() throws Exception {
	StaticApplicationContext context = new StaticApplicationContext();
	context.registerBeanDefinition("scheduler", new RootBeanDefinition(SchedulerFactoryBean.class));
	Scheduler bean = context.getBean("scheduler", Scheduler.class);
	assertFalse(bean.isStarted());
	context.refresh();
	assertTrue(bean.isStarted());
}
 
Example 11
Source File: ScheduledAnnotationBeanPostProcessorTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
private void severalFixedRates(StaticApplicationContext context,
		BeanDefinition processorDefinition, BeanDefinition targetDefinition) {

	context.registerBeanDefinition("postProcessor", processorDefinition);
	context.registerBeanDefinition("target", targetDefinition);
	context.refresh();

	ScheduledTaskHolder postProcessor = context.getBean("postProcessor", ScheduledTaskHolder.class);
	assertEquals(2, postProcessor.getScheduledTasks().size());

	Object target = context.getBean("target");
	ScheduledTaskRegistrar registrar = (ScheduledTaskRegistrar)
			new DirectFieldAccessor(postProcessor).getPropertyValue("registrar");
	@SuppressWarnings("unchecked")
	List<IntervalTask> fixedRateTasks = (List<IntervalTask>)
			new DirectFieldAccessor(registrar).getPropertyValue("fixedRateTasks");
	assertEquals(2, fixedRateTasks.size());
	IntervalTask task1 = fixedRateTasks.get(0);
	ScheduledMethodRunnable runnable1 = (ScheduledMethodRunnable) task1.getRunnable();
	Object targetObject = runnable1.getTarget();
	Method targetMethod = runnable1.getMethod();
	assertEquals(target, targetObject);
	assertEquals("fixedRate", targetMethod.getName());
	assertEquals(0, task1.getInitialDelay());
	assertEquals(4000L, task1.getInterval());
	IntervalTask task2 = fixedRateTasks.get(1);
	ScheduledMethodRunnable runnable2 = (ScheduledMethodRunnable) task2.getRunnable();
	targetObject = runnable2.getTarget();
	targetMethod = runnable2.getMethod();
	assertEquals(target, targetObject);
	assertEquals("fixedRate", targetMethod.getName());
	assertEquals(2000L, task2.getInitialDelay());
	assertEquals(4000L, task2.getInterval());
}
 
Example 12
Source File: QuartzSupportTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
@SuppressWarnings("resource")
public void schedulerAutoStartupFalse() throws Exception {
	StaticApplicationContext context = new StaticApplicationContext();
	BeanDefinition beanDefinition = BeanDefinitionBuilder.genericBeanDefinition(SchedulerFactoryBean.class)
			.addPropertyValue("autoStartup", false).getBeanDefinition();
	context.registerBeanDefinition("scheduler", beanDefinition);
	Scheduler bean = context.getBean("scheduler", Scheduler.class);
	assertFalse(bean.isStarted());
	context.refresh();
	assertFalse(bean.isStarted());
}
 
Example 13
Source File: ApplicationContextEventTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void lambdaAsListenerWithJava8StyleClassCastMessage() {
	StaticApplicationContext context = new StaticApplicationContext();
	ApplicationListener<ApplicationEvent> listener =
			event -> { throw new ClassCastException(event.getClass().getName()); };
	context.addApplicationListener(listener);
	context.refresh();

	context.publishEvent(new MyEvent(context));
	context.close();
}
 
Example 14
Source File: QueueMessageHandlerTest.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
@Test
void receiveMessage_methodAnnotatedWithSqsListenerContainingMultipleQueueNames_methodInvokedForEachQueueName() {
	StaticApplicationContext applicationContext = new StaticApplicationContext();
	applicationContext.registerSingleton(
			"incomingMessageHandlerWithMultipleQueueNames",
			IncomingMessageHandlerWithMultipleQueueNames.class);
	applicationContext.registerSingleton("queueMessageHandler",
			QueueMessageHandler.class);
	applicationContext.refresh();

	QueueMessageHandler queueMessageHandler = applicationContext
			.getBean(QueueMessageHandler.class);
	IncomingMessageHandlerWithMultipleQueueNames incomingMessageHandler = applicationContext
			.getBean(IncomingMessageHandlerWithMultipleQueueNames.class);

	queueMessageHandler.handleMessage(MessageBuilder
			.withPayload("Hello from queue one!")
			.setHeader(QueueMessageHandler.LOGICAL_RESOURCE_ID, "queueOne").build());
	assertThat(incomingMessageHandler.getLastReceivedMessage())
			.isEqualTo("Hello from queue one!");

	queueMessageHandler.handleMessage(MessageBuilder
			.withPayload("Hello from queue two!")
			.setHeader(QueueMessageHandler.LOGICAL_RESOURCE_ID, "queueTwo").build());
	assertThat(incomingMessageHandler.getLastReceivedMessage())
			.isEqualTo("Hello from queue two!");
}
 
Example 15
Source File: QueueMessageHandlerTest.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
@Test
void receiveMessage_withHeadersAsArgumentAnnotation_shouldReceiveAllHeaders() {
	// Arrange
	StaticApplicationContext applicationContext = new StaticApplicationContext();
	applicationContext.registerSingleton("messageHandlerWithHeadersAnnotation",
			MessageReceiverWithHeadersAnnotation.class);
	applicationContext.registerSingleton("queueMessageHandler",
			QueueMessageHandler.class);
	applicationContext.refresh();

	QueueMessageHandler queueMessageHandler = applicationContext
			.getBean(QueueMessageHandler.class);
	MessageReceiverWithHeadersAnnotation messageReceiver = applicationContext
			.getBean(MessageReceiverWithHeadersAnnotation.class);

	// Act
	queueMessageHandler
			.handleMessage(MessageBuilder.withPayload("Hello from a sender")
					.setHeader(QueueMessageHandler.LOGICAL_RESOURCE_ID, "testQueue")
					.setHeader("SenderId", "ID").setHeader("SentTimestamp", "1000")
					.setHeader("ApproximateFirstReceiveTimestamp", "2000").build());

	// Assert
	assertThat(messageReceiver.getHeaders()).isNotNull();
	assertThat(messageReceiver.getHeaders().get("SenderId")).isEqualTo("ID");
	assertThat(
			messageReceiver.getHeaders().get(QueueMessageHandler.LOGICAL_RESOURCE_ID))
					.isEqualTo("testQueue");
}
 
Example 16
Source File: RqueueMessageHandlerTest.java    From rqueue with Apache License 2.0 5 votes vote down vote up
@Test
public void testMethodHavingSpelGettingEvaluated() {
  StaticApplicationContext applicationContext = new StaticApplicationContext();
  applicationContext.registerSingleton("spelMessageHandler", SpelMessageHandler.class);
  applicationContext.registerSingleton("rqueueMessageHandler", RqueueMessageHandler.class);
  applicationContext.refresh();
  MessageHandler messageHandler = applicationContext.getBean(MessageHandler.class);
  SpelMessageHandler messageListener = applicationContext.getBean(SpelMessageHandler.class);
  messageHandler.handleMessage(buildMessage(slowQueue, message));
  assertEquals(message, messageListener.getLastReceivedMessage());
  messageListener.setLastReceivedMessage(null);
  messageHandler.handleMessage(buildMessage(smartQueue, message + message));
  assertEquals(message + message, messageListener.getLastReceivedMessage());
}
 
Example 17
Source File: ProxyControllerTests.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Before
public void onSetUp() throws Exception {
    this.proxyController = new ProxyController();
    this.proxyController
    .setCentralAuthenticationService(getCentralAuthenticationService());

    final StaticApplicationContext context = new StaticApplicationContext();
    context.refresh();
    this.proxyController.setApplicationContext(context);
}
 
Example 18
Source File: QualifierAnnotationTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void testQualifiedByFieldName() {
	StaticApplicationContext context = new StaticApplicationContext();
	BeanDefinitionReader reader = new XmlBeanDefinitionReader(context);
	reader.loadBeanDefinitions(CONFIG_LOCATION);
	context.registerSingleton("testBean", QualifiedByFieldNameTestBean.class);
	context.refresh();
	QualifiedByFieldNameTestBean testBean = (QualifiedByFieldNameTestBean) context.getBean("testBean");
	Person person = testBean.getLarry();
	assertEquals("LarryBean", person.getName());
}
 
Example 19
Source File: QualifierAnnotationTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testQualifiedByAnnotation() {
	StaticApplicationContext context = new StaticApplicationContext();
	BeanDefinitionReader reader = new XmlBeanDefinitionReader(context);
	reader.loadBeanDefinitions(CONFIG_LOCATION);
	context.registerSingleton("testBean", QualifiedByAnnotationTestBean.class);
	context.refresh();
	QualifiedByAnnotationTestBean testBean = (QualifiedByAnnotationTestBean) context.getBean("testBean");
	Person person = testBean.getLarry();
	assertEquals("LarrySpecial", person.getName());
}
 
Example 20
Source File: AutoProxyCreatorTests.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Test
public void testBeanNameAutoProxyCreator() {
	StaticApplicationContext sac = new StaticApplicationContext();
	sac.registerSingleton("testInterceptor", TestInterceptor.class);

	RootBeanDefinition proxyCreator = new RootBeanDefinition(BeanNameAutoProxyCreator.class);
	proxyCreator.getPropertyValues().add("interceptorNames", "testInterceptor");
	proxyCreator.getPropertyValues().add("beanNames", "singletonToBeProxied,innerBean,singletonFactoryToBeProxied");
	sac.getDefaultListableBeanFactory().registerBeanDefinition("beanNameAutoProxyCreator", proxyCreator);

	RootBeanDefinition bd = new RootBeanDefinition(TestBean.class);
	bd.setAutowireMode(RootBeanDefinition.AUTOWIRE_BY_TYPE);
	RootBeanDefinition innerBean = new RootBeanDefinition(TestBean.class);
	bd.getPropertyValues().add("spouse", new BeanDefinitionHolder(innerBean, "innerBean"));
	sac.getDefaultListableBeanFactory().registerBeanDefinition("singletonToBeProxied", bd);

	sac.registerSingleton("singletonFactoryToBeProxied", DummyFactory.class);
	sac.registerSingleton("autowiredIndexedTestBean", IndexedTestBean.class);

	sac.refresh();

	MessageSource messageSource = (MessageSource) sac.getBean("messageSource");
	ITestBean singletonToBeProxied = (ITestBean) sac.getBean("singletonToBeProxied");
	assertFalse(Proxy.isProxyClass(messageSource.getClass()));
	assertTrue(Proxy.isProxyClass(singletonToBeProxied.getClass()));
	assertTrue(Proxy.isProxyClass(singletonToBeProxied.getSpouse().getClass()));

	// test whether autowiring succeeded with auto proxy creation
	assertEquals(sac.getBean("autowiredIndexedTestBean"), singletonToBeProxied.getNestedIndexedBean());

	TestInterceptor ti = (TestInterceptor) sac.getBean("testInterceptor");
	// already 2: getSpouse + getNestedIndexedBean calls above
	assertEquals(2, ti.nrOfInvocations);
	singletonToBeProxied.getName();
	singletonToBeProxied.getSpouse().getName();
	assertEquals(5, ti.nrOfInvocations);

	ITestBean tb = (ITestBean) sac.getBean("singletonFactoryToBeProxied");
	assertTrue(AopUtils.isJdkDynamicProxy(tb));
	assertEquals(5, ti.nrOfInvocations);
	tb.getAge();
	assertEquals(6, ti.nrOfInvocations);

	ITestBean tb2 = (ITestBean) sac.getBean("singletonFactoryToBeProxied");
	assertSame(tb, tb2);
	assertEquals(6, ti.nrOfInvocations);
	tb2.getAge();
	assertEquals(7, ti.nrOfInvocations);
}