Example usage for org.springframework.context.annotation AnnotationConfigApplicationContext getBean

List of usage examples for org.springframework.context.annotation AnnotationConfigApplicationContext getBean

Introduction

In this page you can find the example usage for org.springframework.context.annotation AnnotationConfigApplicationContext getBean.

Prototype

@Override
    public <T> T getBean(String name, Class<T> requiredType) throws BeansException 

Source Link

Usage

From source file:nats.client.spring.JavaConfigAnnotationConfigTest.java

@Test
public void subscribeAnnotationNamedNatsBean() {
    final AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
            NamedNatsAnnotationConfig.class);
    try {/*w w  w .jav a2 s.  c  om*/
        final Nats nats = context.getBean(NATS_BEAN, Nats.class);
        final Nats wrongNats = context.getBean(WRONG_NATS_BEAN, Nats.class);
        wrongNats.publish("test", "Should not get processed");
        testNatsConfig(context, nats);
    } finally {
        context.close();
    }
}

From source file:com.acme.ModuleConfigurationTest.java

@Test
public void test() {
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
    Properties properties = new Properties();
    properties.put("prefix", "foo");
    properties.put("suffix", "bar");
    context.getEnvironment().getPropertySources().addLast(new PropertiesPropertySource("options", properties));
    context.register(TestConfiguration.class);
    context.refresh();/*from   w w  w .  ja  va 2s  .c  om*/

    MessageChannel input = context.getBean("input", MessageChannel.class);
    SubscribableChannel output = context.getBean("output", SubscribableChannel.class);

    final AtomicBoolean handled = new AtomicBoolean();
    output.subscribe(new MessageHandler() {
        @Override
        public void handleMessage(Message<?> message) throws MessagingException {
            handled.set(true);
            assertEquals("foohellobar", message.getPayload());
        }
    });
    input.send(new GenericMessage<String>("hello"));
    assertTrue(handled.get());
}

From source file:com.cloudera.cli.validator.Main.java

/**
 * From the arguments, run the validation.
 *
 * @param args command line arguments//from w w  w  .jav a 2s. c o m
 * @throws IOException anything goes wrong with streams.
 * @return exit code
 */
public int run(String[] args) throws IOException {
    Writer writer = new OutputStreamWriter(outStream, Constants.CHARSET_UTF_8);
    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
    try {
        BeanDefinition cmdOptsbeanDefinition = BeanDefinitionBuilder
                .rootBeanDefinition(CommandLineOptions.class).addConstructorArgValue(appName)
                .addConstructorArgValue(args).getBeanDefinition();
        ctx.registerBeanDefinition(CommandLineOptions.BEAN_NAME, cmdOptsbeanDefinition);
        ctx.register(ApplicationConfiguration.class);
        ctx.refresh();
        CommandLineOptions cmdOptions = ctx.getBean(CommandLineOptions.BEAN_NAME, CommandLineOptions.class);
        CommandLineOptions.Mode mode = cmdOptions.getMode();
        if (mode == null) {
            throw new ParseException("No valid command line arguments");
        }
        ValidationRunner runner = ctx.getBean(mode.runnerName, ValidationRunner.class);
        boolean success = runner.run(cmdOptions.getCommandLineOptionActiveTarget(), writer);
        if (success) {
            writer.write("Validation succeeded.\n");
        }
        return success ? 0 : -1;
    } catch (BeanCreationException e) {
        String cause = e.getMessage();
        if (e.getCause() instanceof BeanInstantiationException) {
            BeanInstantiationException bie = (BeanInstantiationException) e.getCause();
            cause = bie.getMessage();
            if (bie.getCause() != null) {
                cause = bie.getCause().getMessage();
            }
        }
        IOUtils.write(cause + "\n", errStream);
        CommandLineOptions.printUsageMessage(appName, errStream);
        return -2;
    } catch (ParseException e) {
        LOG.debug("Exception", e);
        IOUtils.write(e.getMessage() + "\n", errStream);
        CommandLineOptions.printUsageMessage(appName, errStream);
        return -2;
    } finally {
        if (ctx != null) {
            ctx.close();
        }
        writer.close();
    }
}

From source file:pl.bristleback.server.bristle.conf.runner.ServerInstanceResolver.java

public BristlebackServerInstance resolverServerInstance() {
    InitialConfiguration initialConfiguration = initialConfigurationResolver.resolveConfiguration();
    startLogger(initialConfiguration);/*w  w  w  .ja v  a  2 s. c o m*/

    AnnotationConfigApplicationContext frameworkContext = new AnnotationConfigApplicationContext();
    BristleSpringIntegration springIntegration = new BristleSpringIntegration(actualApplicationContext,
            frameworkContext);
    BristlebackBeanFactoryPostProcessor bristlebackPostProcessor = new BristlebackBeanFactoryPostProcessor(
            initialConfiguration, springIntegration);
    frameworkContext.addBeanFactoryPostProcessor(bristlebackPostProcessor);
    frameworkContext.register(SpringConfigurationResolver.class);
    frameworkContext.scan(InitialConfiguration.SYSTEM_BASE_PACKAGES);
    frameworkContext.refresh();

    BristlebackConfig configuration = frameworkContext.getBean("bristlebackConfigurationFinal",
            BristlebackConfig.class);
    return new BristlebackServerInstance(configuration);
}

From source file:org.springframework.integration.configuration.EnableIntegrationTests.java

@Test
public void testParentChildAnnotationConfiguration() {
    AnnotationConfigApplicationContext child = new AnnotationConfigApplicationContext();
    child.register(ChildConfiguration.class);
    child.setParent(this.context);
    child.refresh();/*from  ww  w.j  av a2  s.c o m*/
    AbstractMessageChannel foo = child.getBean("foo", AbstractMessageChannel.class);
    ChannelInterceptor baz = child.getBean("baz", ChannelInterceptor.class);
    assertTrue(foo.getChannelInterceptors().contains(baz));
    assertFalse(this.output.getChannelInterceptors().contains(baz));
    child.close();
}

From source file:org.springframework.integration.configuration.EnableIntegrationTests.java

@Test
public void testParentChildAnnotationConfigurationFromAnotherPackage() {
    AnnotationConfigApplicationContext child = new AnnotationConfigApplicationContext();
    child.register(org.springframework.integration.configuration2.ChildConfiguration.class);
    child.setParent(this.context);
    child.refresh();//from  ww w  . j  av  a 2s .co m
    AbstractMessageChannel foo = child.getBean("foo", AbstractMessageChannel.class);
    ChannelInterceptor baz = child.getBean("baz", ChannelInterceptor.class);
    assertTrue(foo.getChannelInterceptors().contains(baz));
    assertFalse(this.output.getChannelInterceptors().contains(baz));
    child.close();
}

From source file:org.springframework.integration.mqtt.MqttAdapterTests.java

@SuppressWarnings("unchecked")
@Test/*ww w  . j  a va  2s.  c  o  m*/
public void testCustomExpressions() {
    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(Config.class);
    MqttPahoMessageHandler handler = ctx.getBean("handler", MqttPahoMessageHandler.class);
    GenericMessage<String> message = new GenericMessage<>("foo");
    assertEquals("fooTopic", TestUtils.getPropertyValue(handler, "topicProcessor", MessageProcessor.class)
            .processMessage(message));
    assertEquals(1, TestUtils.getPropertyValue(handler, "converter.qosProcessor", MessageProcessor.class)
            .processMessage(message));
    assertEquals(Boolean.TRUE,
            TestUtils.getPropertyValue(handler, "converter.retainedProcessor", MessageProcessor.class)
                    .processMessage(message));

    handler = ctx.getBean("handlerWithNullExpressions", MqttPahoMessageHandler.class);
    assertEquals(1, TestUtils.getPropertyValue(handler, "converter", DefaultPahoMessageConverter.class)
            .fromMessage(message, null).getQos());
    assertEquals(Boolean.TRUE,
            TestUtils.getPropertyValue(handler, "converter", DefaultPahoMessageConverter.class)
                    .fromMessage(message, null).isRetained());
    ctx.close();
}

From source file:org.springframework.statemachine.listener.ListenerTests.java

@Test
public void testStateEvents() {
    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(Config1.class);
    assertTrue(ctx.containsBean(StateMachineSystemConstants.DEFAULT_ID_STATEMACHINE));
    @SuppressWarnings("unchecked")
    ObjectStateMachine<TestStates, TestEvents> machine = ctx
            .getBean(StateMachineSystemConstants.DEFAULT_ID_STATEMACHINE, ObjectStateMachine.class);
    machine.start();/*  w w w.  jav a 2s.  c o  m*/

    TestStateMachineListener listener = new TestStateMachineListener();
    machine.addStateListener(listener);

    assertThat(machine, notNullValue());
    machine.sendEvent(MessageBuilder.withPayload(TestEvents.E1).setHeader("foo", "jee1").build());
    assertThat(listener.states.size(), is(1));
    assertThat(listener.states.get(0).from.getIds(), contains(TestStates.S1));
    assertThat(listener.states.get(0).to.getIds(), contains(TestStates.S2));
    machine.sendEvent(MessageBuilder.withPayload(TestEvents.E2).setHeader("foo", "jee2").build());
    assertThat(listener.states.size(), is(2));
    assertThat(listener.states.get(1).from.getIds(), contains(TestStates.S2));
    assertThat(listener.states.get(1).to.getIds(), contains(TestStates.S3));
    machine.sendEvent(MessageBuilder.withPayload(TestEvents.E4).setHeader("foo", "jee2").build());
    assertThat(listener.states.size(), is(2));

    ctx.close();
}

From source file:org.springframework.statemachine.listener.ListenerTests.java

@Test
public void testStartEndEvents() throws Exception {
    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(Config2.class);
    assertTrue(ctx.containsBean(StateMachineSystemConstants.DEFAULT_ID_STATEMACHINE));
    @SuppressWarnings("unchecked")
    ObjectStateMachine<TestStates, TestEvents> machine = ctx
            .getBean(StateMachineSystemConstants.DEFAULT_ID_STATEMACHINE, ObjectStateMachine.class);

    TestStateMachineListener listener = new TestStateMachineListener();
    machine.addStateListener(listener);/*from   ww  w .jav a  2 s  .c o  m*/

    machine.start();
    machine.sendEvent(TestEvents.E1);
    machine.sendEvent(TestEvents.E2);
    assertThat(listener.stopLatch.await(2, TimeUnit.SECONDS), is(true));
    assertThat(listener.started, is(1));
    assertThat(listener.stopped, is(1));
    ctx.close();
}

From source file:org.springframework.statemachine.listener.ListenerTests.java

@Test
public void testExtendedStateEvents() throws Exception {
    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(Config2.class);
    assertTrue(ctx.containsBean(StateMachineSystemConstants.DEFAULT_ID_STATEMACHINE));
    @SuppressWarnings("unchecked")
    ObjectStateMachine<TestStates, TestEvents> machine = ctx
            .getBean(StateMachineSystemConstants.DEFAULT_ID_STATEMACHINE, ObjectStateMachine.class);

    TestStateMachineListener listener = new TestStateMachineListener();
    machine.addStateListener(listener);//from  w  w w .  ja v  a 2s.c om
    machine.start();

    machine.getExtendedState().getVariables().put("foo", "jee");
    assertThat(listener.extendedLatch.await(2, TimeUnit.SECONDS), is(true));
    assertThat(listener.extended.size(), is(1));
    assertThat(listener.extended.get(0).key, is("foo"));
    assertThat(listener.extended.get(0).value, is("jee"));
    ctx.close();
}