Java Code Examples for org.springframework.context.support.StaticApplicationContext#registerSingleton()
The following examples show how to use
org.springframework.context.support.StaticApplicationContext#registerSingleton() .
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: LifecycleEventTests.java From java-technology-stack with MIT License | 6 votes |
@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 2
Source File: RqueueMessageHandlerTest.java From rqueue with Apache License 2.0 | 6 votes |
@Test public void testMethodHavingMultipleQueueNames() { StaticApplicationContext applicationContext = new StaticApplicationContext(); applicationContext.registerSingleton("incomingMessageHandler", IncomingMessageHandler.class); applicationContext.registerSingleton("rqueueMessageHandler", RqueueMessageHandler.class); applicationContext.refresh(); MessageHandler messageHandler = applicationContext.getBean(MessageHandler.class); IncomingMessageHandler messageListener = applicationContext.getBean(IncomingMessageHandler.class); messageListener.setExceptionHandlerCalled(false); messageHandler.handleMessage(buildMessage(slowQueue, message)); assertEquals(message, messageListener.getLastReceivedMessage()); messageListener.setLastReceivedMessage(null); messageHandler.handleMessage(buildMessage(smartQueue, message + message)); assertEquals(message + message, messageListener.getLastReceivedMessage()); }
Example 3
Source File: RqueueMessageHandlerTest.java From rqueue with Apache License 2.0 | 6 votes |
@Test public void testMethodHavingNameFromPropertyFile() { StaticApplicationContext applicationContext = new StaticApplicationContext(); applicationContext.registerSingleton("messageHandler", MessageHandlersWithProperty.class); applicationContext.registerSingleton("rqueueMessageHandler", RqueueMessageHandler.class); Map<String, Object> map = new HashMap<>(); map.put("slow.queue.name", slowQueue); map.put("smart.queue.name", smartQueue); applicationContext .getEnvironment() .getPropertySources() .addLast(new MapPropertySource("test", map)); applicationContext.registerSingleton("ppc", PropertySourcesPlaceholderConfigurer.class); applicationContext.refresh(); MessageHandler messageHandler = applicationContext.getBean(MessageHandler.class); MessageHandlersWithProperty messageListener = applicationContext.getBean(MessageHandlersWithProperty.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 4
Source File: RqueueMessageHandlerTest.java From rqueue with Apache License 2.0 | 6 votes |
@Test public void testMethodHavingAllPropertiesSet() { StaticApplicationContext applicationContext = new StaticApplicationContext(); applicationContext.registerSingleton("messageHandler", MessageHandlerWithPlaceHolders.class); applicationContext.registerSingleton("rqueueMessageHandler", DummyMessageHandler.class); Map<String, Object> map = new HashMap<>(); map.put("queue.name", slowQueue + "," + smartQueue); map.put("queue.dead.letter.queue", true); map.put("queue.num.retries", 3); map.put("queue.visibility.timeout", "30*30*60"); map.put("dead.letter.queue.name", slowQueue + "-dlq"); applicationContext .getEnvironment() .getPropertySources() .addLast(new MapPropertySource("test", map)); applicationContext.refresh(); DummyMessageHandler messageHandler = applicationContext.getBean(DummyMessageHandler.class); assertEquals(3, messageHandler.mappingInformation.getNumRetry()); Set<String> queueNames = new HashSet<>(); queueNames.add(slowQueue); queueNames.add(smartQueue); assertEquals(queueNames, messageHandler.mappingInformation.getQueueNames()); assertEquals(30 * 30 * 60L, messageHandler.mappingInformation.getVisibilityTimeout()); assertEquals(slowQueue + "-dlq", messageHandler.mappingInformation.getDeadLetterQueueName()); }
Example 5
Source File: LifecycleEventTests.java From spring-analysis-note with MIT License | 5 votes |
@Test public void contextStartedEvent() { 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()); assertEquals(0, listener.getStartedCount()); context.start(); assertTrue(lifecycleBean.isRunning()); assertEquals(1, listener.getStartedCount()); assertSame(context, listener.getApplicationContext()); }
Example 6
Source File: ResourcePathFactoryBeanTest.java From cougar with Apache License 2.0 | 5 votes |
@Test public void simplePositiveCase() { StaticApplicationContext c = new StaticApplicationContext(); MutablePropertyValues pvs = new MutablePropertyValues(); pvs.addPropertyValue("path", "classpath:" + RESOURCE); c.registerSingleton("myResource", ResourcePathFactoryBean.class, pvs); c.refresh(); // From the spring app context this value should come out as a string String path = (String) c.getBean("myResource"); // You dont want to assert the full path but probably want to check if it has the file name in it assertTrue(path.endsWith(RESOURCE)); }
Example 7
Source File: SimpleStorageProtocolResolverConfigurerTest.java From spring-cloud-aws with Apache License 2.0 | 5 votes |
@Test void postProcessBeans_beanWithMethodInjectedResourceLoader_receivesSimpleStorageResourceLoader() { // Arrange StaticApplicationContext staticApplicationContext = new StaticApplicationContext(); configureApplicationContext(staticApplicationContext); staticApplicationContext.registerSingleton("client", MethodInjectionTarget.class); staticApplicationContext.refresh(); // Act MethodInjectionTarget methodInjectionTarget = staticApplicationContext .getBean(MethodInjectionTarget.class); // Assert assertThat(methodInjectionTarget.getResourceLoader()).isNotNull(); assertThat(DefaultResourceLoader.class .isInstance(methodInjectionTarget.getResourceLoader())).isTrue(); assertThat(DefaultResourceLoader.class .isInstance(methodInjectionTarget.getResourceLoader())).isTrue(); DefaultResourceLoader defaultResourceLoader = (DefaultResourceLoader) methodInjectionTarget .getResourceLoader(); assertThat(SimpleStorageProtocolResolver.class.isInstance( defaultResourceLoader.getProtocolResolvers().iterator().next())).isTrue(); }
Example 8
Source File: SimpleMessageListenerContainerTest.java From spring-cloud-aws with Apache License 2.0 | 5 votes |
@Test void start_withAQueueNameThatIsAlreadyRunning_shouldNotStartTheQueueAgainAndIgnoreTheCall() throws Exception { // Arrange StaticApplicationContext applicationContext = new StaticApplicationContext(); applicationContext.registerSingleton("testMessageListener", TestMessageListener.class); SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(); AmazonSQSAsync sqs = mock(AmazonSQSAsync.class, withSettings().stubOnly()); when(sqs.receiveMessage(any(ReceiveMessageRequest.class))) .thenReturn(new ReceiveMessageResult()); container.setAmazonSqs(sqs); container.setBackOffTime(0); QueueMessageHandler messageHandler = new QueueMessageHandler(); messageHandler.setApplicationContext(applicationContext); container.setMessageHandler(messageHandler); mockGetQueueUrl(sqs, "testQueue", "https://start_withAQueueNameThatIsAlreadyRunning_shouldNotStartTheQueueAgainAndIgnoreTheCall.amazonaws.com"); mockGetQueueAttributesWithEmptyResult(sqs, "https://start_withAQueueNameThatIsAlreadyRunning_shouldNotStartTheQueueAgainAndIgnoreTheCall.amazonaws.com"); messageHandler.afterPropertiesSet(); container.afterPropertiesSet(); container.start(); assertThat(container.isRunning("testQueue")).isTrue(); // Act container.start("testQueue"); // Assert assertThat(container.isRunning("testQueue")).isTrue(); container.stop(); }
Example 9
Source File: QualifierAnnotationTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Test public void testQualifiedByBeanName() { StaticApplicationContext context = new StaticApplicationContext(); BeanDefinitionReader reader = new XmlBeanDefinitionReader(context); reader.loadBeanDefinitions(CONFIG_LOCATION); context.registerSingleton("testBean", QualifiedByBeanNameTestBean.class); context.refresh(); QualifiedByBeanNameTestBean testBean = (QualifiedByBeanNameTestBean) context.getBean("testBean"); Person person = testBean.getLarry(); assertEquals("LarryBean", person.getName()); assertTrue(testBean.myProps != null && testBean.myProps.isEmpty()); }
Example 10
Source File: QualifierAnnotationTests.java From spring-analysis-note with MIT License | 5 votes |
@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 11
Source File: ResourcePathFactoryBeanTest.java From cougar with Apache License 2.0 | 5 votes |
@Test(expected = BeanCreationException.class) public void nullOrEmptyValueforPath() { StaticApplicationContext c = new StaticApplicationContext(); c.registerSingleton("myResource", ResourcePathFactoryBean.class); c.refresh(); // From the spring app context this value should come out as a string c.getBean("myResource"); }
Example 12
Source File: QualifierAnnotationTests.java From java-technology-stack with MIT License | 5 votes |
@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 13
Source File: QualifierAnnotationTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Test public void testQualifiedByAlias() { StaticApplicationContext context = new StaticApplicationContext(); BeanDefinitionReader reader = new XmlBeanDefinitionReader(context); reader.loadBeanDefinitions(CONFIG_LOCATION); context.registerSingleton("testBean", QualifiedByAliasTestBean.class); context.refresh(); QualifiedByAliasTestBean testBean = (QualifiedByAliasTestBean) context.getBean("testBean"); Person person = testBean.getStooge(); assertEquals("LarryBean", person.getName()); }
Example 14
Source File: QualifierAnnotationTests.java From java-technology-stack with MIT License | 5 votes |
@Test public void testQualifiedByAnnotationValue() { StaticApplicationContext context = new StaticApplicationContext(); BeanDefinitionReader reader = new XmlBeanDefinitionReader(context); reader.loadBeanDefinitions(CONFIG_LOCATION); context.registerSingleton("testBean", QualifiedByAnnotationValueTestBean.class); context.refresh(); QualifiedByAnnotationValueTestBean testBean = (QualifiedByAnnotationValueTestBean) context.getBean("testBean"); Person person = testBean.getLarry(); assertEquals("LarrySpecial", person.getName()); }
Example 15
Source File: SimpleStorageProtocolResolverConfigurerTest.java From spring-cloud-aws with Apache License 2.0 | 5 votes |
@Test void postProcessBeans_beanWithConstructorInjectedResourceLoader_receivesSimpleStorageResourceLoader() { // Arrange StaticApplicationContext staticApplicationContext = new StaticApplicationContext(); configureApplicationContext(staticApplicationContext); staticApplicationContext.registerSingleton("client", ConstructorInjectionTarget.class); staticApplicationContext.refresh(); // Act ConstructorInjectionTarget constructorInjectionTarget = staticApplicationContext .getBean(ConstructorInjectionTarget.class); // Assert assertThat(constructorInjectionTarget.getResourceLoader()).isNotNull(); assertThat(DefaultResourceLoader.class .isInstance(constructorInjectionTarget.getResourceLoader())).isTrue(); assertThat(DefaultResourceLoader.class .isInstance(constructorInjectionTarget.getResourceLoader())).isTrue(); DefaultResourceLoader defaultResourceLoader = (DefaultResourceLoader) constructorInjectionTarget .getResourceLoader(); assertThat(SimpleStorageProtocolResolver.class.isInstance( defaultResourceLoader.getProtocolResolvers().iterator().next())).isTrue(); }
Example 16
Source File: QualifierAnnotationTests.java From java-technology-stack with MIT License | 5 votes |
@Test public void testQualifiedByAlias() { StaticApplicationContext context = new StaticApplicationContext(); BeanDefinitionReader reader = new XmlBeanDefinitionReader(context); reader.loadBeanDefinitions(CONFIG_LOCATION); context.registerSingleton("testBean", QualifiedByAliasTestBean.class); context.refresh(); QualifiedByAliasTestBean testBean = (QualifiedByAliasTestBean) context.getBean("testBean"); Person person = testBean.getStooge(); assertEquals("LarryBean", person.getName()); }
Example 17
Source File: QueueMessageHandlerTest.java From spring-cloud-aws with Apache License 2.0 | 5 votes |
@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 18
Source File: SimpleMessageListenerContainerTest.java From spring-cloud-aws with Apache License 2.0 | 4 votes |
@Test void stop_withContainerHavingMultipleQueuesRunning_shouldStopQueuesInParallel() throws Exception { // Arrange StaticApplicationContext applicationContext = new StaticApplicationContext(); applicationContext.registerSingleton("testMessageListener", TestMessageListener.class); applicationContext.registerSingleton("anotherTestMessageListener", AnotherTestMessageListener.class); CountDownLatch testQueueCountdownLatch = new CountDownLatch(1); CountDownLatch anotherTestQueueCountdownLatch = new CountDownLatch(1); CountDownLatch spinningThreadsStarted = new CountDownLatch(2); SimpleMessageListenerContainer container = new SimpleMessageListenerContainer() { @Override public void stopQueue(String logicalQueueName) { if ("testQueue".equals(logicalQueueName)) { testQueueCountdownLatch.countDown(); } else if ("anotherTestQueue".equals(logicalQueueName)) { anotherTestQueueCountdownLatch.countDown(); } super.stopQueue(logicalQueueName); } }; AmazonSQSAsync sqs = mock(AmazonSQSAsync.class, withSettings().stubOnly()); container.setAmazonSqs(sqs); container.setBackOffTime(100); container.setQueueStopTimeout(5000); QueueMessageHandler messageHandler = new QueueMessageHandler(); messageHandler.setApplicationContext(applicationContext); container.setMessageHandler(messageHandler); mockGetQueueUrl(sqs, "testQueue", "http://testQueue.amazonaws.com"); mockGetQueueUrl(sqs, "anotherTestQueue", "https://anotherTestQueue.amazonaws.com"); mockGetQueueAttributesWithEmptyResult(sqs, "http://testQueue.amazonaws.com"); mockGetQueueAttributesWithEmptyResult(sqs, "https://anotherTestQueue.amazonaws.com"); when(sqs.receiveMessage( new ReceiveMessageRequest("http://testQueue.amazonaws.com") .withAttributeNames("All").withMessageAttributeNames("All") .withMaxNumberOfMessages(10))) .thenAnswer((Answer<ReceiveMessageResult>) invocation -> { spinningThreadsStarted.countDown(); testQueueCountdownLatch.await(1, TimeUnit.SECONDS); throw new OverLimitException("Boom"); }); when(sqs.receiveMessage( new ReceiveMessageRequest("https://anotherTestQueue.amazonaws.com") .withAttributeNames("All").withMessageAttributeNames("All") .withMaxNumberOfMessages(10))) .thenAnswer((Answer<ReceiveMessageResult>) invocation -> { spinningThreadsStarted.countDown(); anotherTestQueueCountdownLatch.await(1, TimeUnit.SECONDS); throw new OverLimitException("Boom"); }); messageHandler.afterPropertiesSet(); container.afterPropertiesSet(); container.start(); spinningThreadsStarted.await(1, TimeUnit.SECONDS); StopWatch stopWatch = new StopWatch(); // Act stopWatch.start(); container.stop(); stopWatch.stop(); // Assert assertThat(stopWatch.getTotalTimeMillis() < 200) .as("Stop time must be shorter than stopping one queue after the other") .isTrue(); }
Example 19
Source File: AutoProxyCreatorTests.java From spring4-understanding with Apache License 2.0 | 4 votes |
@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); }
Example 20
Source File: SimpleMessageListenerContainerTest.java From spring-cloud-aws with Apache License 2.0 | 4 votes |
@Test void setQueueStopTimeout_withNotDefaultTimeout_mustBeUsedWhenStoppingAQueue() throws Exception { // Arrange StaticApplicationContext applicationContext = new StaticApplicationContext(); applicationContext.registerSingleton("longRunningListenerMethod", LongRunningListenerMethod.class); SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(); AmazonSQSAsync sqs = mock(AmazonSQSAsync.class, withSettings().stubOnly()); container.setAmazonSqs(sqs); container.setBackOffTime(0); container.setQueueStopTimeout(100); QueueMessageHandler messageHandler = new QueueMessageHandler(); messageHandler.setApplicationContext(applicationContext); container.setMessageHandler(messageHandler); mockGetQueueUrl(sqs, "longRunningQueueMessage", "https://setQueueStopTimeout_withNotDefaultTimeout_mustBeUsedWhenStoppingAQueue.amazonaws.com"); mockGetQueueAttributesWithEmptyResult(sqs, "https://setQueueStopTimeout_withNotDefaultTimeout_mustBeUsedWhenStoppingAQueue.amazonaws.com"); mockReceiveMessage(sqs, "https://setQueueStopTimeout_withNotDefaultTimeout_mustBeUsedWhenStoppingAQueue.amazonaws.com", "Hello", "ReceiptHandle"); messageHandler.afterPropertiesSet(); container.afterPropertiesSet(); container.start(); applicationContext.getBean(LongRunningListenerMethod.class).getCountDownLatch() .await(1, TimeUnit.SECONDS); StopWatch stopWatch = new StopWatch(); // Act stopWatch.start(); container.stop("longRunningQueueMessage"); stopWatch.stop(); // Assert assertThat(container.getQueueStopTimeout()).isEqualTo(100); assertThat(stopWatch.getTotalTimeMillis() >= container.getQueueStopTimeout()) .as("stop must last at least the defined queue stop timeout (> 100ms)") .isTrue(); assertThat(stopWatch .getTotalTimeMillis() < LongRunningListenerMethod.LISTENER_METHOD_WAIT_TIME) .as("stop must last less than the listener method (< 10000ms)") .isTrue(); container.stop(); }