Java Code Examples for org.springframework.context.support.StaticApplicationContext#getBean()
The following examples show how to use
org.springframework.context.support.StaticApplicationContext#getBean() .
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: ApplicationContextEventTests.java From java-technology-stack with MIT License | 6 votes |
@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 2
Source File: AsyncAnnotationBeanPostProcessorTests.java From java-technology-stack with MIT License | 6 votes |
@Test public void invokedAsynchronouslyOnProxyTarget() { StaticApplicationContext context = new StaticApplicationContext(); context.registerBeanDefinition("postProcessor", new RootBeanDefinition(AsyncAnnotationBeanPostProcessor.class)); TestBean tb = new TestBean(); ProxyFactory pf = new ProxyFactory(ITestBean.class, (MethodInterceptor) invocation -> invocation.getMethod().invoke(tb, invocation.getArguments())); context.registerBean("target", ITestBean.class, () -> (ITestBean) pf.getProxy()); context.refresh(); ITestBean testBean = context.getBean("target", ITestBean.class); testBean.test(); Thread mainThread = Thread.currentThread(); testBean.await(3000); Thread asyncThread = testBean.getThread(); assertNotSame(mainThread, asyncThread); context.close(); }
Example 3
Source File: RqueueMessageHandlerTest.java From rqueue with Apache License 2.0 | 6 votes |
@Test public void testMethodHavingNameFromPropertyFileWithExpression() { StaticApplicationContext applicationContext = new StaticApplicationContext(); applicationContext.registerSingleton( "messageHandler", MessageHandlerWithExpressionProperty.class); applicationContext.registerSingleton("rqueueMessageHandler", RqueueMessageHandler.class); applicationContext .getEnvironment() .getPropertySources() .addLast(new MapPropertySource("test", Collections.singletonMap("queueName", slowQueue))); applicationContext.registerSingleton("ppc", PropertySourcesPlaceholderConfigurer.class); applicationContext.refresh(); MessageHandler messageHandler = applicationContext.getBean(MessageHandler.class); MessageHandlerWithExpressionProperty messageListener = applicationContext.getBean(MessageHandlerWithExpressionProperty.class); messageHandler.handleMessage(buildMessage(slowQueue, message)); assertEquals(message, messageListener.getLastReceivedMessage()); }
Example 4
Source File: QueueMessageHandlerTest.java From spring-cloud-aws with Apache License 2.0 | 5 votes |
@Test void processHandlerMethodException_invocableHandlerMethodNotAvailable_errorMustBeLogged() { // Arrange StaticApplicationContext applicationContext = new StaticApplicationContext(); applicationContext.registerSingleton("sqsListenerWithoutMessageExceptionHandler", SqsListenerWithoutMessageExceptionHandler.class); applicationContext.registerBeanDefinition("queueMessageHandler", getQueueMessageHandlerBeanDefinition()); applicationContext.refresh(); MessageHandler messageHandler = applicationContext.getBean(MessageHandler.class); LoggerContext logContext = (LoggerContext) LoggerFactory.getILoggerFactory(); ListAppender<ILoggingEvent> appender = new ListAppender<>(); appender.start(); Logger log = logContext.getLogger(QueueMessageHandler.class); log.setLevel(Level.ERROR); log.addAppender(appender); appender.setContext(log.getLoggerContext()); // Act assertThatThrownBy( () -> messageHandler .handleMessage(MessageBuilder.withPayload("testContent") .setHeader(QueueMessageHandler.LOGICAL_RESOURCE_ID, "receive") .build())).isInstanceOf(MessagingException.class); // Assert assertThat(appender.list).hasSize(1); }
Example 5
Source File: QualifierAnnotationTests.java From java-technology-stack with MIT License | 5 votes |
@Test public void testQualifiedByCustomValue() { StaticApplicationContext context = new StaticApplicationContext(); BeanDefinitionReader reader = new XmlBeanDefinitionReader(context); reader.loadBeanDefinitions(CONFIG_LOCATION); context.registerSingleton("testBean", QualifiedByCustomValueTestBean.class); context.refresh(); QualifiedByCustomValueTestBean testBean = (QualifiedByCustomValueTestBean) context.getBean("testBean"); Person person = testBean.getCurly(); assertEquals("Curly", person.getName()); }
Example 6
Source File: QualifierAnnotationTests.java From java-technology-stack with MIT License | 5 votes |
@Test public void testQualifiedByParameterName() { StaticApplicationContext context = new StaticApplicationContext(); BeanDefinitionReader reader = new XmlBeanDefinitionReader(context); reader.loadBeanDefinitions(CONFIG_LOCATION); context.registerSingleton("testBean", QualifiedByParameterNameTestBean.class); context.refresh(); QualifiedByParameterNameTestBean testBean = (QualifiedByParameterNameTestBean) context.getBean("testBean"); Person person = testBean.getLarry(); assertEquals("LarryBean", person.getName()); }
Example 7
Source File: QueueMessageHandlerTest.java From spring-cloud-aws with Apache License 2.0 | 5 votes |
@Test void receiveMessage_methodAnnotatedWithSqsListenerContainingExpression_methodInvokedOnResolvedExpression() { // Arrange StaticApplicationContext applicationContext = new StaticApplicationContext(); applicationContext.getEnvironment().getPropertySources() .addLast(new MapPropertySource("test", Collections.singletonMap("myQueue", "resolvedQueue"))); applicationContext.registerSingleton( "incomingMessageHandlerWithMultipleQueueNames", IncomingMessageHandlerWithExpressionName.class); applicationContext.registerSingleton("queueMessageHandler", QueueMessageHandler.class); applicationContext.refresh(); QueueMessageHandler queueMessageHandler = applicationContext .getBean(QueueMessageHandler.class); // Act queueMessageHandler.handleMessage(MessageBuilder .withPayload("Hello from resolved queue!") .setHeader(QueueMessageHandler.LOGICAL_RESOURCE_ID, "resolvedQueue") .build()); // Assert IncomingMessageHandlerWithExpressionName incomingMessageHandler = applicationContext .getBean(IncomingMessageHandlerWithExpressionName.class); assertThat(incomingMessageHandler.getLastReceivedMessage()) .isEqualTo("Hello from resolved queue!"); }
Example 8
Source File: LifecycleEventTests.java From spring4-understanding with Apache License 2.0 | 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 9
Source File: QualifierAnnotationTests.java From spring-analysis-note 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 10
Source File: QualifierAnnotationTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Test public void testQualifiedByParameterName() { StaticApplicationContext context = new StaticApplicationContext(); BeanDefinitionReader reader = new XmlBeanDefinitionReader(context); reader.loadBeanDefinitions(CONFIG_LOCATION); context.registerSingleton("testBean", QualifiedByParameterNameTestBean.class); context.refresh(); QualifiedByParameterNameTestBean testBean = (QualifiedByParameterNameTestBean) context.getBean("testBean"); Person person = testBean.getLarry(); assertEquals("LarryBean", person.getName()); }
Example 11
Source File: AutoProxyCreatorTests.java From spring-analysis-note with MIT License | 5 votes |
@Test public void testAutoProxyCreatorWithFallbackToDynamicProxy() { StaticApplicationContext sac = new StaticApplicationContext(); MutablePropertyValues pvs = new MutablePropertyValues(); pvs.add("proxyFactoryBean", "false"); sac.registerSingleton("testAutoProxyCreator", TestAutoProxyCreator.class, pvs); sac.registerSingleton("noInterfaces", NoInterfaces.class); sac.registerSingleton("containerCallbackInterfacesOnly", ContainerCallbackInterfacesOnly.class); sac.registerSingleton("singletonNoInterceptor", CustomProxyFactoryBean.class); sac.registerSingleton("singletonToBeProxied", CustomProxyFactoryBean.class); sac.registerPrototype("prototypeToBeProxied", SpringProxyFactoryBean.class); sac.refresh(); MessageSource messageSource = (MessageSource) sac.getBean("messageSource"); NoInterfaces noInterfaces = (NoInterfaces) sac.getBean("noInterfaces"); ContainerCallbackInterfacesOnly containerCallbackInterfacesOnly = (ContainerCallbackInterfacesOnly) sac.getBean("containerCallbackInterfacesOnly"); ITestBean singletonNoInterceptor = (ITestBean) sac.getBean("singletonNoInterceptor"); ITestBean singletonToBeProxied = (ITestBean) sac.getBean("singletonToBeProxied"); ITestBean prototypeToBeProxied = (ITestBean) sac.getBean("prototypeToBeProxied"); assertFalse(AopUtils.isCglibProxy(messageSource)); assertTrue(AopUtils.isCglibProxy(noInterfaces)); assertTrue(AopUtils.isCglibProxy(containerCallbackInterfacesOnly)); assertFalse(AopUtils.isCglibProxy(singletonNoInterceptor)); assertFalse(AopUtils.isCglibProxy(singletonToBeProxied)); assertFalse(AopUtils.isCglibProxy(prototypeToBeProxied)); TestAutoProxyCreator tapc = (TestAutoProxyCreator) sac.getBean("testAutoProxyCreator"); assertEquals(0, tapc.testInterceptor.nrOfInvocations); singletonNoInterceptor.getName(); assertEquals(0, tapc.testInterceptor.nrOfInvocations); singletonToBeProxied.getAge(); assertEquals(1, tapc.testInterceptor.nrOfInvocations); prototypeToBeProxied.getSpouse(); assertEquals(2, tapc.testInterceptor.nrOfInvocations); }
Example 12
Source File: ApplicationContextEventTests.java From java-technology-stack with MIT License | 5 votes |
@Test public void innerBeanAsListener() { StaticApplicationContext context = new StaticApplicationContext(); RootBeanDefinition listenerDef = new RootBeanDefinition(TestBean.class); listenerDef.getPropertyValues().add("friends", new RootBeanDefinition(BeanThatListens.class)); context.registerBeanDefinition("listener", listenerDef); context.refresh(); context.publishEvent(new MyEvent(this)); context.publishEvent(new MyEvent(this)); TestBean listener = context.getBean(TestBean.class); assertEquals(3, ((BeanThatListens) listener.getFriends().iterator().next()).getEventCount()); context.close(); }
Example 13
Source File: QualifierAnnotationTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Test public void testQualifiedByValue() { StaticApplicationContext context = new StaticApplicationContext(); BeanDefinitionReader reader = new XmlBeanDefinitionReader(context); reader.loadBeanDefinitions(CONFIG_LOCATION); context.registerSingleton("testBean", QualifiedByValueTestBean.class); context.refresh(); QualifiedByValueTestBean testBean = (QualifiedByValueTestBean) context.getBean("testBean"); Person person = testBean.getLarry(); assertEquals("Larry", person.getName()); }
Example 14
Source File: QualifierAnnotationTests.java From java-technology-stack with MIT License | 5 votes |
@Test public void testQualifiedByValue() { StaticApplicationContext context = new StaticApplicationContext(); BeanDefinitionReader reader = new XmlBeanDefinitionReader(context); reader.loadBeanDefinitions(CONFIG_LOCATION); context.registerSingleton("testBean", QualifiedByValueTestBean.class); context.refresh(); QualifiedByValueTestBean testBean = (QualifiedByValueTestBean) context.getBean("testBean"); Person person = testBean.getLarry(); assertEquals("Larry", person.getName()); }
Example 15
Source File: AutoProxyCreatorTests.java From spring-analysis-note with MIT License | 5 votes |
@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 16
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 17
Source File: AsyncAnnotationBeanPostProcessorTests.java From java-technology-stack with MIT License | 5 votes |
@Test public void taskExecutorByBeanName() { 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 executorDefinition2 = new RootBeanDefinition(ThreadPoolTaskExecutor.class); executorDefinition2.getPropertyValues().add("threadNamePrefix", "testExecutor2"); context.registerBeanDefinition("taskExecutor", executorDefinition2); 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("testExecutor2")); context.close(); }
Example 18
Source File: SimpleMessageListenerContainerTest.java From spring-cloud-aws with Apache License 2.0 | 4 votes |
@Test void receiveMessage_withMessageListenerMethodAndVisibilityProlonging_callsChangeMessageVisibility() throws Exception { // Arrange CountDownLatch countDownLatch = new CountDownLatch(1); SimpleMessageListenerContainer container = new SimpleMessageListenerContainer() { @Override protected void executeMessage( org.springframework.messaging.Message<String> stringMessage) { countDownLatch.countDown(); super.executeMessage(stringMessage); } }; AmazonSQSAsync sqs = mock(AmazonSQSAsync.class); container.setAmazonSqs(sqs); QueueMessageHandler messageHandler = new QueueMessageHandler(); container.setMessageHandler(messageHandler); StaticApplicationContext applicationContext = new StaticApplicationContext(); applicationContext.registerSingleton("testListener", TestMessageListenerWithVisibilityProlong.class); mockGetQueueUrl(sqs, "testQueue", "https://receiveMessage_withMessageListenerMethodAnd" + "VisibilityProlonging_callsChangeMessageVisibility.amazonaws.com"); mockGetQueueAttributesWithEmptyResult(sqs, "https://receiveMessage_withMessageListenerMethodAnd" + "VisibilityProlonging_callsChangeMessageVisibility.amazonaws.com"); messageHandler.setApplicationContext(applicationContext); messageHandler.afterPropertiesSet(); container.afterPropertiesSet(); mockReceiveMessage(sqs, "https://receiveMessage_withMessageListenerMethodAnd" + "VisibilityProlonging_callsChangeMessageVisibility.amazonaws.com", "messageContent", "ReceiptHandle"); // Act container.start(); // Assert countDownLatch.await(1L, TimeUnit.SECONDS); verify(sqs, never()) .changeMessageVisibilityAsync(any(ChangeMessageVisibilityRequest.class)); TestMessageListenerWithVisibilityProlong testMessageListenerWithVisibilityProlong = applicationContext .getBean(TestMessageListenerWithVisibilityProlong.class); testMessageListenerWithVisibilityProlong.getCountDownLatch().await(1L, TimeUnit.SECONDS); testMessageListenerWithVisibilityProlong.extend(5); verify(sqs, times(1)) .changeMessageVisibilityAsync(eq(new ChangeMessageVisibilityRequest( "https://receiveMessage_withMessageListenerMethodAnd" + "VisibilityProlonging_callsChangeMessageVisibility.amazonaws.com", "ReceiptHandle", 5))); container.stop(); }
Example 19
Source File: RqueueMessageListenerContainerTest.java From rqueue with Apache License 2.0 | 4 votes |
@Test public void testMessageFetcherRetryWorking() throws Exception { AtomicInteger fastQueueCounter = new AtomicInteger(0); String fastQueueMessage = "This is fast queue"; RqueueMessage message = new RqueueMessage(fastQueue, fastQueueMessage, null, null); RqueueMessageTemplate rqueueMessageTemplate = mock(RqueueMessageTemplate.class); StaticApplicationContext applicationContext = new StaticApplicationContext(); applicationContext.registerSingleton("rqueueConfig", RqueueConfig.class); applicationContext.registerSingleton("messageHandler", RqueueMessageHandler.class); applicationContext.registerSingleton("fastMessageListener", FastMessageListener.class); applicationContext.registerSingleton( "rqueueMessageMetadataService", RqueueMessageMetadataService.class); applicationContext.registerSingleton( "applicationEventPublisher", ApplicationEventPublisher.class); RqueueMessageHandler messageHandler = applicationContext.getBean("messageHandler", RqueueMessageHandler.class); messageHandler.setApplicationContext(applicationContext); messageHandler.afterPropertiesSet(); RqueueMessageListenerContainer container = createContainer(messageHandler, rqueueMessageTemplate); doAnswer( invocation -> { if (fastQueueCounter.get() < 2) { if (fastQueueCounter.incrementAndGet() == 1) { throw new RedisCommandExecutionException("Some error occurred"); } return message; } return null; }) .when(rqueueMessageTemplate) .pop(fastQueue, fastProcessingQueue, fastProcessingQueueChannel, 900000L); FastMessageListener fastMessageListener = applicationContext.getBean("fastMessageListener", FastMessageListener.class); container.afterPropertiesSet(); container.start(); waitFor(() -> fastQueueCounter.get() == 2, "fastQueue message fetch"); waitFor( () -> fastQueueMessage.equals(fastMessageListener.getLastMessage()), "message to be consumed"); container.stop(); container.doDestroy(); }
Example 20
Source File: SimpleMessageListenerContainerTest.java From spring-cloud-aws with Apache License 2.0 | 4 votes |
@Test void receiveMessage_withMessageListenerMethodAndNeverDeletionPolicy_waitsForAcknowledgmentBeforeDeletion() throws Exception { // Arrange CountDownLatch countDownLatch = new CountDownLatch(1); SimpleMessageListenerContainer container = new SimpleMessageListenerContainer() { @Override protected void executeMessage( org.springframework.messaging.Message<String> stringMessage) { countDownLatch.countDown(); super.executeMessage(stringMessage); } }; AmazonSQSAsync sqs = mock(AmazonSQSAsync.class); container.setAmazonSqs(sqs); QueueMessageHandler messageHandler = new QueueMessageHandler(); container.setMessageHandler(messageHandler); StaticApplicationContext applicationContext = new StaticApplicationContext(); applicationContext.registerSingleton("testListener", TestMessageListenerWithManualDeletionPolicy.class); mockGetQueueUrl(sqs, "testQueue", "https://receiveMessage_withMessageListenerMethodAnd" + "NeverDeletionPolicy_waitsForAcknowledgmentBeforeDeletion.amazonaws.com"); mockGetQueueAttributesWithEmptyResult(sqs, "https://receiveMessage_withMessageListenerMethodAnd" + "NeverDeletionPolicy_waitsForAcknowledgmentBeforeDeletion.amazonaws.com"); messageHandler.setApplicationContext(applicationContext); messageHandler.afterPropertiesSet(); container.afterPropertiesSet(); mockReceiveMessage(sqs, "https://receiveMessage_withMessageListenerMethodAnd" + "NeverDeletionPolicy_waitsForAcknowledgmentBeforeDeletion.amazonaws.com", "messageContent", "ReceiptHandle"); // Act container.start(); // Assert countDownLatch.await(1L, TimeUnit.SECONDS); verify(sqs, never()).deleteMessageAsync(eq(new DeleteMessageRequest( "https://receiveMessage_withMessageListenerMethodAnd" + "NeverDeletionPolicy_waitsForAcknowledgmentBeforeDeletion.amazonaws.com", "ReceiptHandle")), any(AsyncHandler.class)); TestMessageListenerWithManualDeletionPolicy testMessageListenerWithManualDeletionPolicy = applicationContext .getBean(TestMessageListenerWithManualDeletionPolicy.class); testMessageListenerWithManualDeletionPolicy.getCountDownLatch().await(1L, TimeUnit.SECONDS); testMessageListenerWithManualDeletionPolicy.acknowledge(); verify(sqs, times(1)).deleteMessageAsync(eq(new DeleteMessageRequest( "https://receiveMessage_withMessageListenerMethodAnd" + "NeverDeletionPolicy_waitsForAcknowledgmentBeforeDeletion.amazonaws.com", "ReceiptHandle")), any(AsyncHandler.class)); container.stop(); }