io.micronaut.context.ApplicationContext.getBean()方法的使用及代码示例

x33g5p2x  于2022-01-16 转载在 其他  
字(11.2k)|赞(0)|评价(0)|浏览(117)

本文整理了Java中io.micronaut.context.ApplicationContext.getBean()方法的一些代码示例,展示了ApplicationContext.getBean()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。ApplicationContext.getBean()方法的具体详情如下:
包路径:io.micronaut.context.ApplicationContext
类名称:ApplicationContext
方法名:getBean

ApplicationContext.getBean介绍

暂无

代码示例

代码示例来源:origin: micronaut-projects/micronaut-core

/**
 * This method is designed to be called when using the {@link FunctionInitializer} from a static Application main method.
 *
 * @param args     The arguments passed to main
 * @param supplier The function that executes this function
 * @throws IOException If an error occurs
 */
protected void run(String[] args, Function<ParseContext, ?> supplier) throws IOException {
  ApplicationContext applicationContext = this.applicationContext;
  this.functionExitHandler = applicationContext.findBean(FunctionExitHandler.class).orElse(this.functionExitHandler);
  ParseContext context = new ParseContext(args);
  try {
    Object result = supplier.apply(context);
    if (result != null) {
      LocalFunctionRegistry bean = applicationContext.getBean(LocalFunctionRegistry.class);
      StreamFunctionExecutor.encode(applicationContext.getEnvironment(), bean, result.getClass(), result, System.out);
      functionExitHandler.exitWithSuccess();
    }
  } catch (Exception e) {
    functionExitHandler.exitWithError(e, context.debug);
  }
}

代码示例来源:origin: micronaut-projects/micronaut-core

LocalFunctionRegistry localFunctionRegistry = applicationContext.getBean(LocalFunctionRegistry.class);
ExecutableMethod<Object, Object> method = resolveFunction(localFunctionRegistry, functionName);
Class<?> returnJavaType = method.getReturnType().getType();
Class<Object> functionType = method.getDeclaringType();
BeanDefinition<Object> beanDefinition = applicationContext.getBeanDefinition(functionType, qualifier);
Object bean = applicationContext.getBean(functionType, qualifier);
List<Argument<?>> typeArguments = beanDefinition.getTypeArguments();

代码示例来源:origin: micronaut-projects/micronaut-core

/**
 * Get.
 *
 * @param type type
 * @param <T> generic return type
 * @return Type
 */
public final <T> T get(Class<T> type) {
  if (ClassUtils.isJavaLangType(type)) {
    return applicationContext
      .getConversionService()
      .convert(data, type).orElseThrow(() -> newIllegalArgument(type, data));
  } else {
    MediaTypeCodecRegistry codecRegistry = applicationContext.getBean(MediaTypeCodecRegistry.class);
    return codecRegistry.findCodec(MediaType.APPLICATION_JSON_TYPE)
      .map(codec -> {
        if (data != null) {
          return codec.decode(type, data);
        } else {
          // try System.in
          return codec.decode(type, System.in);
        }
      })
      .orElseThrow(() -> newIllegalArgument(type, data));
  }
}

代码示例来源:origin: micronaut-projects/micronaut-core

@Test
  public void testSenderAttributes() throws Exception {

    try(EmbeddedServer embeddedServer = ApplicationContext.run(EmbeddedServer.class)) {
      StoryClient client = embeddedServer.getApplicationContext().getBean(StoryClient.class);
      StoryClientFilter filter = embeddedServer.getApplicationContext().getBean(StoryClientFilter.class);

      Story story = client.getById("jan2019").blockingGet();

      Assert.assertNotNull(story);

      Map<String, Object> attributes = filter.getLatestRequestAttributes();
      Assert.assertNotNull(attributes);
      Assert.assertEquals("jan2019", attributes.get("story-id"));
      Assert.assertEquals("storyClient", attributes.get("client-name"));
      Assert.assertEquals("1", attributes.get("version"));
    }
  }
}

代码示例来源:origin: micronaut-projects/micronaut-core

@Test
  public void testSenderHeaders() throws Exception {

    Map<String,Object> config =Collections.singletonMap(
        "pet.client.id", "11"
    );

    try(EmbeddedServer embeddedServer = ApplicationContext.run(EmbeddedServer.class, config)) {
      PetClient client = embeddedServer.getApplicationContext().getBean(PetClient.class);

      Pet pet = client.get("Fred").blockingGet();

      Assert.assertNotNull(pet);

      Assert.assertEquals(pet.getAge(), 11);
    }

  }
}

代码示例来源:origin: micronaut-projects/micronaut-core

@Test
public void testClientAnnotationStreaming() throws Exception {
  try( EmbeddedServer embeddedServer = ApplicationContext.run(EmbeddedServer.class) ) {
    HeadlineClient headlineClient = embeddedServer
        .getApplicationContext()
        .getBean(HeadlineClient.class);
    Event<Headline> headline = headlineClient.streamHeadlines().blockFirst();
    assertNotNull( headline );
    assertTrue( headline.getData().getText().startsWith("Latest Headline") );
  }
}
// end::streamingClient[]

代码示例来源:origin: micronaut-projects/micronaut-core

@Test
public void testClientAnnotationStreaming() throws Exception {
  try( EmbeddedServer embeddedServer = ApplicationContext.run(EmbeddedServer.class) ) {
    HeadlineClient headlineClient = embeddedServer
                      .getApplicationContext()
                      .getBean(HeadlineClient.class); // <1>
    Maybe<Headline> firstHeadline = headlineClient.streamHeadlines().firstElement(); // <2>
    Headline headline = firstHeadline.blockingGet(); // <3>
    assertNotNull( headline );
    assertTrue( headline.getText().startsWith("Latest Headline") );
  }
}
// end::streamingClient[]

代码示例来源:origin: micronaut-projects/micronaut-core

@Test
  public void testPostPetValidation() {
    EmbeddedServer embeddedServer = ApplicationContext.run(EmbeddedServer.class);
    PetClient client = embeddedServer.getApplicationContext().getBean(PetClient.class);

    // tag::error[]
    thrown.expect(HttpClientResponseException.class);
    thrown.expectMessage("age: must be greater than or equal to 1");
    client.save("Fred", -1).blockingGet();
    // end::error[]

    embeddedServer.stop();
  }
}

代码示例来源:origin: micronaut-projects/micronaut-core

@Test
  public void testGetPojoList() {
    ApplicationContext applicationContext = ApplicationContext.run();
    EmbeddedServer server = applicationContext.getBean(EmbeddedServer.class).start();

    HttpClient client = applicationContext.createBean(HttpClient.class, server.getURL());

    Flowable<HttpResponse<List>> flowable = Flowable.fromPublisher(client.exchange(
        HttpRequest.GET("/get/pojoList"), Argument.of(List.class, HttpGetSpec.Book.class)
    ));
    HttpResponse<List> response = flowable.blockingFirst();

    assertEquals(response.getStatus(), HttpStatus.OK);
    Optional<List> body = response.getBody();
    assertTrue(body.isPresent());

    List<HttpGetSpec.Book> list = body.get();
    assertEquals(list.size(), 1);
    assertTrue(list.get(0) instanceof HttpGetSpec.Book);

    client.stop();
    applicationContext.stop();
  }
}

代码示例来源:origin: micronaut-projects/micronaut-core

@Test
public void testSimpleGet() {
  ApplicationContext applicationContext = ApplicationContext.run();
  EmbeddedServer server = applicationContext.getBean(EmbeddedServer.class).start();
  HttpClient client = new DefaultHttpClient(server.getURL());
  Flowable<HttpResponse<String>> flowable = Flowable.fromPublisher(client.exchange(
      HttpRequest.GET("/get/simple"), String.class
  ));
  HttpResponse<String> response = flowable.blockingFirst();
  Assert.assertEquals(response.getStatus(), HttpStatus.OK);
  Optional<String> body = response.getBody(String.class);
  assertTrue(body.isPresent());
  assertEquals(body.get(), "success");
  client.stop();
  applicationContext.stop();
}

代码示例来源:origin: micronaut-projects/micronaut-core

@Test
public void testPostPet() {
  EmbeddedServer embeddedServer = ApplicationContext.run(EmbeddedServer.class);
  PetClient client = embeddedServer.getApplicationContext().getBean(PetClient.class);
  // tag::post[]
  Pet pet = client.save("Dino", 10).blockingGet();
  assertEquals("Dino", pet.getName());
  assertEquals(10, pet.getAge());
  // end::post[]
  embeddedServer.stop();
}

代码示例来源:origin: micronaut-projects/micronaut-spring

@Override
public void start() {
  if (!isRunning()) {
    micronautContext.start();
    this.beanFactory = micronautContext.getBean(MicronautBeanFactory.class);
    this.environment = micronautContext.getBean(MicronautEnvironment.class);
    this.eventPublisher = micronautContext.getBean(MicronautApplicationEventPublisher.class);
    this.messageSource = micronautContext.findBean(MessageSource.class).orElse(null);
    this.startupDate = System.currentTimeMillis();
  }
}

代码示例来源:origin: io.micronaut.aws/micronaut-function-aws-api-proxy

@Override
public void initialize() throws ContainerInitializationException {
  Timer.start(TIMER_INIT);
  try {
    this.applicationContext = applicationContextBuilder.environments(Environment.FUNCTION)
        .build()
        .start();
    this.lambdaContainerEnvironment.setApplicationContext(applicationContext);
    this.lambdaContainerEnvironment.setJsonCodec(applicationContext.getBean(JsonMediaTypeCodec.class));
    this.lambdaContainerEnvironment.setRouter(applicationContext.getBean(Router.class));
    this.executorService = applicationContext.getBean(ExecutorService.class, Qualifiers.byName(TaskExecutors.IO));
    this.requestArgumentSatisfier = new RequestArgumentSatisfier(
        applicationContext.getBean(RequestBinderRegistry.class)
    );
  } catch (Exception e) {
    throw new ContainerInitializationException(
        "Error starting Micronaut container: " + e.getMessage(),
        e
    );
  }
  Timer.stop(TIMER_INIT);
}

代码示例来源:origin: io.micronaut/micronaut-inject

/**
   * Run the {@link ApplicationContext} with the given type. Returning an instance of the type.
   *
   * @param type         The type of the bean to run
   * @param <T>          The type, a subclass of {@link ApplicationContextLifeCycle}
   * @return The running bean
   */
  default <T extends AutoCloseable> T run(Class<T> type) {
    ApplicationContext applicationContext = start();
    T bean = applicationContext.getBean(type);
    if (bean instanceof LifeCycle) {
      LifeCycle lifeCycle = (LifeCycle) bean;
      if (!lifeCycle.isRunning()) {
        lifeCycle.start();
      }
    }
    return bean;
  }
}

代码示例来源:origin: io.micronaut/inject

/**
   * Run the {@link ApplicationContext} with the given type. Returning an instance of the type.
   *
   * @param type         The type of the bean to run
   * @param <T>          The type, a subclass of {@link ApplicationContextLifeCycle}
   * @return The running bean
   */
  default <T extends AutoCloseable> T run(Class<T> type) {
    ApplicationContext applicationContext = start();
    T bean = applicationContext.getBean(type);
    if (bean instanceof LifeCycle) {
      LifeCycle lifeCycle = (LifeCycle) bean;
      if (!lifeCycle.isRunning()) {
        lifeCycle.start();
      }
    }
    return bean;
  }
}

代码示例来源:origin: io.micronaut/inject

/**
 * Run the {@link ApplicationContext} with the given type. Returning an instance of the type. Note this method
 * should not be used.
 * If the {@link ApplicationContext} requires graceful shutdown unless the returned bean takes responsibility for
 * shutting down the context.
 *
 * @param type           The environment to use
 * @param propertySource Additional properties
 * @param environments   The environment names
 * @param <T>            The type
 * @return The running {@link BeanContext}
 */
static <T extends AutoCloseable> T run(Class<T> type, PropertySource propertySource, String... environments) {
  T bean = build(environments)
    .mainClass(type)
    .propertySources(propertySource)
    .start()
    .getBean(type);
  if (bean != null) {
    if (bean instanceof LifeCycle) {
      LifeCycle lifeCycle = (LifeCycle) bean;
      if (!lifeCycle.isRunning()) {
        lifeCycle.start();
      }
    }
  }
  return bean;
}

代码示例来源:origin: io.micronaut/micronaut-inject

/**
 * Run the {@link ApplicationContext} with the given type. Returning an instance of the type. Note this method
 * should not be used.
 * If the {@link ApplicationContext} requires graceful shutdown unless the returned bean takes responsibility for
 * shutting down the context.
 *
 * @param type           The environment to use
 * @param propertySource Additional properties
 * @param environments   The environment names
 * @param <T>            The type
 * @return The running {@link BeanContext}
 */
static <T extends AutoCloseable> T run(Class<T> type, PropertySource propertySource, String... environments) {
  T bean = build(environments)
    .mainClass(type)
    .propertySources(propertySource)
    .start()
    .getBean(type);
  if (bean != null) {
    if (bean instanceof LifeCycle) {
      LifeCycle lifeCycle = (LifeCycle) bean;
      if (!lifeCycle.isRunning()) {
        lifeCycle.start();
      }
    }
  }
  return bean;
}

相关文章