org.springframework.context.support.StaticApplicationContext Java Examples

The following examples show how to use org.springframework.context.support.StaticApplicationContext. 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: HandlerMethodMappingTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void detectHandlerMethodsInAncestorContexts() {
	StaticApplicationContext cxt = new StaticApplicationContext();
	cxt.registerSingleton("myHandler", MyHandler.class);

	AbstractHandlerMethodMapping<String> mapping1 = new MyHandlerMethodMapping();
	mapping1.setApplicationContext(new StaticApplicationContext(cxt));
	mapping1.afterPropertiesSet();

	assertEquals(0, mapping1.getHandlerMethods().size());

	AbstractHandlerMethodMapping<String> mapping2 = new MyHandlerMethodMapping();
	mapping2.setDetectHandlerMethodsInAncestorContexts(true);
	mapping2.setApplicationContext(new StaticApplicationContext(cxt));
	mapping2.afterPropertiesSet();

	assertEquals(2, mapping2.getHandlerMethods().size());
}
 
Example #2
Source File: QueueMessageHandlerTest.java    From spring-cloud-aws with Apache License 2.0 6 votes vote down vote up
@Test
void receiveMessage_withHeaderAnnotationAsArgument_shouldReceiveRequestedHeader() {
	// Arrange
	StaticApplicationContext applicationContext = new StaticApplicationContext();
	applicationContext.registerSingleton("messageHandlerWithHeaderAnnotation",
			MessageReceiverWithHeaderAnnotation.class);
	applicationContext.registerSingleton("queueMessageHandler",
			QueueMessageHandler.class);
	applicationContext.refresh();

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

	// Act
	queueMessageHandler.handleMessage(MessageBuilder
			.withPayload("Hello from a sender").setHeader("SenderId", "elsUnitTest")
			.setHeader(QueueMessageHandler.LOGICAL_RESOURCE_ID, "testQueue").build());

	// Assert
	assertThat(messageReceiver.getPayload()).isEqualTo("Hello from a sender");
	assertThat(messageReceiver.getSenderId()).isEqualTo("elsUnitTest");
}
 
Example #3
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 #4
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 #5
Source File: RqueueMessageHandlerTest.java    From rqueue with Apache License 2.0 6 votes vote down vote up
@Test
public void concurrencyResolverSingleValue() {
  StaticApplicationContext applicationContext = new StaticApplicationContext();
  applicationContext.registerSingleton("messageHandler", MessageHandlerWithConcurrency.class);
  applicationContext.registerSingleton("rqueueMessageHandler", DummyMessageHandler.class);
  Map<String, Object> map = new HashMap<>();
  map.put("queue.name", slowQueue + "," + smartQueue);
  map.put("queue.concurrency", "5");
  applicationContext
      .getEnvironment()
      .getPropertySources()
      .addLast(new MapPropertySource("test", map));
  applicationContext.refresh();
  DummyMessageHandler messageHandler = applicationContext.getBean(DummyMessageHandler.class);
  assertEquals(new Concurrency(1, 5), messageHandler.mappingInformation.getConcurrency());
}
 
Example #6
Source File: AutoProxyCreatorTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testAutoProxyCreatorWithFactoryBeanAndPrototype() {
	StaticApplicationContext sac = new StaticApplicationContext();
	sac.registerSingleton("testAutoProxyCreator", TestAutoProxyCreator.class);

	MutablePropertyValues pvs = new MutablePropertyValues();
	pvs.add("singleton", "false");
	sac.registerSingleton("prototypeFactoryToBeProxied", DummyFactory.class, pvs);

	sac.refresh();

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

	FactoryBean<?> prototypeFactory = (FactoryBean<?>) sac.getBean("&prototypeFactoryToBeProxied");
	assertTrue(AopUtils.isCglibProxy(prototypeFactory));
	TestBean tb = (TestBean) sac.getBean("prototypeFactoryToBeProxied");
	assertTrue(AopUtils.isCglibProxy(tb));

	assertEquals(2, tapc.testInterceptor.nrOfInvocations);
	tb.getAge();
	assertEquals(3, tapc.testInterceptor.nrOfInvocations);
}
 
Example #7
Source File: ApplicationContextEventTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void anonymousClassAsListener() {
	final Set<MyEvent> seenEvents = new HashSet<>();
	StaticApplicationContext context = new StaticApplicationContext();
	context.addApplicationListener(new ApplicationListener<MyEvent>() {
		@Override
		public void onApplicationEvent(MyEvent event) {
			seenEvents.add(event);
		}
	});
	context.refresh();

	MyEvent event1 = new MyEvent(context);
	context.publishEvent(event1);
	context.publishEvent(new MyOtherEvent(context));
	MyEvent event2 = new MyEvent(context);
	context.publishEvent(event2);
	assertSame(2, seenEvents.size());
	assertTrue(seenEvents.contains(event1));
	assertTrue(seenEvents.contains(event2));

	context.close();
}
 
Example #8
Source File: HandlerMethodMappingTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void detectHandlerMethodsInAncestorContexts() {
	StaticApplicationContext cxt = new StaticApplicationContext();
	cxt.registerSingleton("myHandler", MyHandler.class);

	AbstractHandlerMethodMapping<String> mapping1 = new MyHandlerMethodMapping();
	mapping1.setApplicationContext(new StaticApplicationContext(cxt));
	mapping1.afterPropertiesSet();

	assertEquals(0, mapping1.getHandlerMethods().size());

	AbstractHandlerMethodMapping<String> mapping2 = new MyHandlerMethodMapping();
	mapping2.setDetectHandlerMethodsInAncestorContexts(true);
	mapping2.setApplicationContext(new StaticApplicationContext(cxt));
	mapping2.afterPropertiesSet();

	assertEquals(2, mapping2.getHandlerMethods().size());
}
 
Example #9
Source File: ApplicationContextEventTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void simpleApplicationEventMulticasterWithTaskExecutor() {
	@SuppressWarnings("unchecked")
	ApplicationListener<ApplicationEvent> listener = mock(ApplicationListener.class);
	ApplicationEvent evt = new ContextClosedEvent(new StaticApplicationContext());

	SimpleApplicationEventMulticaster smc = new SimpleApplicationEventMulticaster();
	smc.setTaskExecutor(new Executor() {
		@Override
		public void execute(Runnable command) {
			command.run();
			command.run();
		}
	});
	smc.addApplicationListener(listener);

	smc.multicastEvent(evt);
	verify(listener, times(2)).onApplicationEvent(evt);
}
 
Example #10
Source File: ApplicationContextEventTests.java    From spring4-understanding with Apache License 2.0 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 #11
Source File: ApplicationContextEventTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void listenersInApplicationContextWithPayloadEvents() {
	StaticApplicationContext context = new StaticApplicationContext();
	context.registerBeanDefinition("listener", new RootBeanDefinition(MyPayloadListener.class));
	context.refresh();

	MyPayloadListener listener = context.getBean("listener", MyPayloadListener.class);
	context.publishEvent("event1");
	context.publishEvent("event2");
	context.publishEvent("event3");
	context.publishEvent("event4");
	assertTrue(listener.seenPayloads.contains("event1"));
	assertTrue(listener.seenPayloads.contains("event2"));
	assertTrue(listener.seenPayloads.contains("event3"));
	assertTrue(listener.seenPayloads.contains("event4"));

	AbstractApplicationEventMulticaster multicaster = context.getBean(AbstractApplicationEventMulticaster.class);
	assertEquals(2, multicaster.retrieverCache.size());

	context.close();
}
 
Example #12
Source File: XsltViewResolverTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void resolveView() throws Exception {
	StaticApplicationContext ctx = new StaticApplicationContext();

	String prefix = ClassUtils.classPackageAsResourcePath(getClass());
	String suffix = ".xsl";
	String viewName = "products";

	XsltViewResolver viewResolver = new XsltViewResolver();
	viewResolver.setPrefix(prefix);
	viewResolver.setSuffix(suffix);
	viewResolver.setApplicationContext(ctx);

	XsltView view = (XsltView) viewResolver.resolveViewName(viewName, Locale.ENGLISH);
	assertNotNull("View should not be null", view);
	assertEquals("Incorrect URL", prefix + viewName + suffix, view.getUrl());
}
 
Example #13
Source File: QualifierAnnotationTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testQualifiedByAttributesWithCustomQualifierRegistered() {
	StaticApplicationContext context = new StaticApplicationContext();
	BeanDefinitionReader reader = new XmlBeanDefinitionReader(context);
	reader.loadBeanDefinitions(CONFIG_LOCATION);
	QualifierAnnotationAutowireCandidateResolver resolver = (QualifierAnnotationAutowireCandidateResolver)
			context.getDefaultListableBeanFactory().getAutowireCandidateResolver();
	resolver.addQualifierType(MultipleAttributeQualifier.class);
	context.registerSingleton("testBean", MultiQualifierClient.class);
	context.refresh();

	MultiQualifierClient testBean = (MultiQualifierClient) context.getBean("testBean");

	assertNotNull( testBean.factoryTheta);
	assertNotNull( testBean.implTheta);
}
 
Example #14
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 #15
Source File: AutoProxyCreatorTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testAutoProxyCreatorWithFactoryBean() {
	StaticApplicationContext sac = new StaticApplicationContext();
	sac.registerSingleton("testAutoProxyCreator", TestAutoProxyCreator.class);
	sac.registerSingleton("singletonFactoryToBeProxied", DummyFactory.class);
	sac.refresh();

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

	FactoryBean<?> factory = (FactoryBean<?>) sac.getBean("&singletonFactoryToBeProxied");
	assertTrue(AopUtils.isCglibProxy(factory));

	TestBean tb = (TestBean) sac.getBean("singletonFactoryToBeProxied");
	assertTrue(AopUtils.isCglibProxy(tb));
	assertEquals(2, tapc.testInterceptor.nrOfInvocations);
	tb.getAge();
	assertEquals(3, tapc.testInterceptor.nrOfInvocations);
}
 
Example #16
Source File: LifecycleEventTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void contextStoppedEvent() {
	StaticApplicationContext context = new StaticApplicationContext();
	context.registerSingleton("lifecycle", LifecycleTestBean.class);
	context.registerSingleton("listener", LifecycleListener.class);
	context.refresh();
	LifecycleTestBean lifecycleBean = (LifecycleTestBean) context.getBean("lifecycle");
	LifecycleListener listener = (LifecycleListener) context.getBean("listener");
	assertFalse(lifecycleBean.isRunning());
	context.start();
	assertTrue(lifecycleBean.isRunning());
	assertEquals(0, listener.getStoppedCount());
	context.stop();
	assertFalse(lifecycleBean.isRunning());
	assertEquals(1, listener.getStoppedCount());
	assertSame(context, listener.getApplicationContext());
}
 
Example #17
Source File: QualifierAnnotationTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testQualifiedByAttributesWithCustomQualifierRegistered() {
	StaticApplicationContext context = new StaticApplicationContext();
	BeanDefinitionReader reader = new XmlBeanDefinitionReader(context);
	reader.loadBeanDefinitions(CONFIG_LOCATION);
	QualifierAnnotationAutowireCandidateResolver resolver = (QualifierAnnotationAutowireCandidateResolver)
			context.getDefaultListableBeanFactory().getAutowireCandidateResolver();
	resolver.addQualifierType(MultipleAttributeQualifier.class);
	context.registerSingleton("testBean", MultiQualifierClient.class);
	context.refresh();

	MultiQualifierClient testBean = (MultiQualifierClient) context.getBean("testBean");

	assertNotNull( testBean.factoryTheta);
	assertNotNull( testBean.implTheta);
}
 
Example #18
Source File: AmazonEc2InstanceDataPropertySourcePostProcessorTest.java    From spring-cloud-aws with Apache License 2.0 6 votes vote down vote up
@Test
void postProcessBeanFactory_withConfigurableEnvironment_registersPropertySource()
		throws Exception {
	// Arrange
	StaticApplicationContext staticApplicationContext = new StaticApplicationContext();
	staticApplicationContext.registerSingleton("process",
			AmazonEc2InstanceDataPropertySourcePostProcessor.class);

	// Act
	staticApplicationContext.refresh();

	// Assert
	assertThat(staticApplicationContext.getEnvironment().getPropertySources().get(
			AmazonEc2InstanceDataPropertySourcePostProcessor.INSTANCE_DATA_PROPERTY_SOURCE_NAME))
					.isNotNull();
}
 
Example #19
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 #20
Source File: ViewResolutionResultHandlerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test  // SPR-15291
public void contentNegotiationWithRedirect() {
	HandlerResult handlerResult = new HandlerResult(new Object(), "redirect:/",
			on(Handler.class).annotNotPresent(ModelAttribute.class).resolveReturnType(String.class),
			this.bindingContext);

	UrlBasedViewResolver viewResolver = new UrlBasedViewResolver();
	viewResolver.setApplicationContext(new StaticApplicationContext());
	ViewResolutionResultHandler resultHandler = resultHandler(viewResolver);

	MockServerWebExchange exchange = MockServerWebExchange.from(get("/account").accept(APPLICATION_JSON));
	resultHandler.handleResult(exchange, handlerResult).block(Duration.ZERO);

	MockServerHttpResponse response = exchange.getResponse();
	assertEquals(303, response.getStatusCode().value());
	assertEquals("/", response.getHeaders().getLocation().toString());
}
 
Example #21
Source File: LifecycleEventTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void contextStoppedEvent() {
	StaticApplicationContext context = new StaticApplicationContext();
	context.registerSingleton("lifecycle", LifecycleTestBean.class);
	context.registerSingleton("listener", LifecycleListener.class);
	context.refresh();
	LifecycleTestBean lifecycleBean = (LifecycleTestBean) context.getBean("lifecycle");
	LifecycleListener listener = (LifecycleListener) context.getBean("listener");
	assertFalse(lifecycleBean.isRunning());
	context.start();
	assertTrue(lifecycleBean.isRunning());
	assertEquals(0, listener.getStoppedCount());
	context.stop();
	assertFalse(lifecycleBean.isRunning());
	assertEquals(1, listener.getStoppedCount());
	assertSame(context, listener.getApplicationContext());
}
 
Example #22
Source File: LoggerBeanNamesResolverTest.java    From eclair with Apache License 2.0 6 votes vote down vote up
@Test
public void resolveManyLoggers() {
    // given
    String beanName = "simpleLogger";
    String alias = "logger";
    String beanName2 = "simpleLogger2";
    String alias2 = "logger2";

    GenericApplicationContext applicationContext = new StaticApplicationContext();
    applicationContext.registerBeanDefinition(beanName, givenLoggerBeanDefinition());
    applicationContext.getBeanFactory().registerAlias(beanName, alias);
    applicationContext.registerBeanDefinition(beanName2, givenLoggerBeanDefinition());
    applicationContext.getBeanFactory().registerAlias(beanName2, alias2);
    // when
    Set<String> namesByBeanName = loggerBeanNamesResolver.resolve(applicationContext, beanName);
    // then
    assertThat(namesByBeanName, hasSize(2));
    assertThat(namesByBeanName, containsInAnyOrder(beanName, alias));
}
 
Example #23
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 #24
Source File: WebApplicationObjectSupportTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testWebApplicationObjectSupportWithWrongContext() {
	StaticApplicationContext ac = new StaticApplicationContext();
	ac.registerBeanDefinition("test", new RootBeanDefinition(TestWebApplicationObject.class));
	WebApplicationObjectSupport wao = (WebApplicationObjectSupport) ac.getBean("test");
	try {
		wao.getWebApplicationContext();
		fail("Should have thrown IllegalStateException");
	}
	catch (IllegalStateException ex) {
		// expected
	}
}
 
Example #25
Source File: AutoProxyCreatorTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testAutoProxyCreatorWithFactoryBeanAndProxyObjectOnly() {
	StaticApplicationContext sac = new StaticApplicationContext();

	MutablePropertyValues pvs = new MutablePropertyValues();
	pvs.add("proxyFactoryBean", "false");
	sac.registerSingleton("testAutoProxyCreator", TestAutoProxyCreator.class, pvs);

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

	sac.refresh();

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

	FactoryBean<?> factory = (FactoryBean<?>) sac.getBean("&singletonFactoryToBeProxied");
	assertFalse(AopUtils.isAopProxy(factory));

	TestBean tb = (TestBean) sac.getBean("singletonFactoryToBeProxied");
	assertTrue(AopUtils.isCglibProxy(tb));
	assertEquals(0, tapc.testInterceptor.nrOfInvocations);
	tb.getAge();
	assertEquals(1, tapc.testInterceptor.nrOfInvocations);

	TestBean tb2 = (TestBean) sac.getBean("singletonFactoryToBeProxied");
	assertSame(tb, tb2);
	assertEquals(1, tapc.testInterceptor.nrOfInvocations);
	tb2.getAge();
	assertEquals(2, tapc.testInterceptor.nrOfInvocations);
}
 
Example #26
Source File: MessageBrokerConfigurationTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void simpValidatorMvc() {
	StaticApplicationContext appCxt = new StaticApplicationContext();
	appCxt.registerSingleton("mvcValidator", TestValidator.class);
	AbstractMessageBrokerConfiguration config = new BaseTestMessageBrokerConfig() {};
	config.setApplicationContext(appCxt);

	assertThat(config.simpValidator(), Matchers.notNullValue());
	assertThat(config.simpValidator(), Matchers.instanceOf(TestValidator.class));
}
 
Example #27
Source File: RqueueMessageHandlerTest.java    From rqueue with Apache License 2.0 5 votes vote down vote up
@Test(expected = BeanCreationException.class)
public void concurrencyResolverInvalidValue() {
  StaticApplicationContext applicationContext = new StaticApplicationContext();
  applicationContext.registerSingleton("messageHandler", MessageHandlerWithConcurrency.class);
  applicationContext.registerSingleton("rqueueMessageHandler", DummyMessageHandler.class);
  Map<String, Object> map = new HashMap<>();
  map.put("queue.name", slowQueue + "," + smartQueue);
  map.put("queue.concurrency", slowQueue);
  applicationContext
      .getEnvironment()
      .getPropertySources()
      .addLast(new MapPropertySource("test", map));
  applicationContext.refresh();
}
 
Example #28
Source File: EventPublicationInterceptorTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void testExpectedBehavior() throws Exception {
	TestBean target = new TestBean();
	final TestListener listener = new TestListener();

	class TestContext extends StaticApplicationContext {
		@Override
		protected void onRefresh() throws BeansException {
			addApplicationListener(listener);
		}
	}

	StaticApplicationContext ctx = new TestContext();
	MutablePropertyValues pvs = new MutablePropertyValues();
	pvs.add("applicationEventClass", TestEvent.class.getName());
	// should automatically receive applicationEventPublisher reference
	ctx.registerSingleton("publisher", EventPublicationInterceptor.class, pvs);
	ctx.registerSingleton("otherListener", FactoryBeanTestListener.class);
	ctx.refresh();

	EventPublicationInterceptor interceptor =
			(EventPublicationInterceptor) ctx.getBean("publisher");
	ProxyFactory factory = new ProxyFactory(target);
	factory.addAdvice(0, interceptor);

	ITestBean testBean = (ITestBean) factory.getProxy();

	// invoke any method on the advised proxy to see if the interceptor has been invoked
	testBean.getAge();

	// two events: ContextRefreshedEvent and TestEvent
	assertTrue("Interceptor must have published 2 events", listener.getEventCount() == 2);
	TestListener otherListener = (TestListener) ctx.getBean("&otherListener");
	assertTrue("Interceptor must have published 2 events", otherListener.getEventCount() == 2);
}
 
Example #29
Source File: BeanNameUrlHandlerMappingTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void requestsWithSubPathsInParentContext() throws Exception {
	BeanNameUrlHandlerMapping hm = new BeanNameUrlHandlerMapping();
	hm.setDetectHandlersInAncestorContexts(true);
	hm.setApplicationContext(new StaticApplicationContext(wac));
	doTestRequestsWithSubPaths(hm);
}
 
Example #30
Source File: QuartzSupportTests.java    From spring4-understanding with Apache License 2.0 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());
}