本文整理了Java中io.micronaut.context.ApplicationContext
类的一些代码示例,展示了ApplicationContext
类的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。ApplicationContext
类的具体详情如下:
包路径:io.micronaut.context.ApplicationContext
类名称:ApplicationContext
[英]An application context extends a BeanContext and adds the concepts of configuration, environments and runtimes.
The ApplicationContext is the main entry point for starting and running Micronaut applications. It can be though of as a container object for all dependency injected objects.
The ApplicationContext can be started via the #run() method. For example:
ApplicationContext context = ApplicationContext.run();
Alternatively, the #build() method can be used to customize the ApplicationContext using the ApplicationContextBuilder interface prior to running. For example:
ApplicationContext context = ApplicationContext.build().environments("test").start();
The #getEnvironment() method can be used to obtain a reference to the application Environment, which contains the loaded configuration and active environment names.
[中]应用程序上下文扩展BeanContext并添加配置、环境和运行时的概念。
ApplicationContext是启动和运行Micronaut应用程序的主要入口点。它可以作为所有依赖注入对象的容器对象。
ApplicationContext可以通过#run()方法启动。例如:
ApplicationContext context = ApplicationContext.run();
或者,可以使用#build()方法在运行前使用ApplicationContextBuilder界面自定义ApplicationContext。例如:
ApplicationContext context = ApplicationContext.build().environments("test").start();
可以使用#getEnvironment()方法获取对应用程序环境的引用,其中包含加载的配置和活动环境名称。
代码示例来源:origin: micronaut-projects/micronaut-core
private static void instrumentAnnotationMetadata(BeanContext beanContext, ExecutableMethod<?, ?> method) {
if (beanContext instanceof ApplicationContext && method instanceof EnvironmentConfigurable) {
// ensure metadata is environment aware
((EnvironmentConfigurable) method).configure(((ApplicationContext) beanContext).getEnvironment());
}
}
代码示例来源: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
/**
* Builds a new builder.
*
* @return The {@link ApplicationContextBuilder}
*/
protected @Nonnull ApplicationContextBuilder newApplicationContextBuilder() {
return ApplicationContext.build(Environment.FUNCTION);
}
代码示例来源:origin: micronaut-projects/micronaut-core
/**
* Start the environment specified.
* @param applicationContext the application context with the environment
* @return The environment within the context
*/
protected Environment startEnvironment(ApplicationContext applicationContext) {
if (!applicationContext.isRunning()) {
if (this instanceof PropertySource) {
applicationContext.getEnvironment().addPropertySource((PropertySource) this);
}
return applicationContext
.start()
.getEnvironment();
} else {
return applicationContext.getEnvironment();
}
}
}
代码示例来源:origin: micronaut-projects/micronaut-core
/**
* Main method.
* @param args The arguments
*/
public static void main(String... args) {
// enable Graal class analysis
System.setProperty(GraalClassLoadingReporter.GRAAL_CLASS_ANALYSIS, Boolean.TRUE.toString());
if (ArrayUtils.isNotEmpty(args)) {
System.setProperty(GraalClassLoadingReporter.REFLECTION_JSON_FILE, args[0]);
}
try {
ApplicationContext applicationContext = ApplicationContext.run();
// following beans may impact classloading, so load them.
applicationContext.findBean(EmbeddedServer.class);
applicationContext.getBeansOfType(ExecutableMethodProcessor.class);
// finish up
applicationContext.stop();
} catch (Throwable e) {
System.err.println("An error occurred analyzing class requirements: " + e.getMessage());
e.printStackTrace(System.err);
}
}
代码示例来源: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
@BeforeClass
public static void setupServer() {
System.setProperty(Environment.BOOTSTRAP_CONTEXT_PROPERTY, "true");
Map<String, Object> map = new HashMap<>();
map.put(MockSpringCloudConfigServer.ENABLED, true);
map.put("micronaut.server.port", -1);
map.put("spring.cloud.config.enabled", false);
map.put("micronaut.environments", "dev,test");
springCloudServer = ApplicationContext.run(EmbeddedServer.class, map);
server = ApplicationContext.run(EmbeddedServer.class, CollectionUtils.mapOf(
"micronaut.environments","test",
"micronaut.application.name", "spring-config-sample",
"micronaut.config-client.enabled", true,
"spring.cloud.config.enabled", true,
"spring.cloud.config.uri", springCloudServer.getURI()
));
client = server
.getApplicationContext()
.createBean(HttpClient.class, LoadBalancer.fixed(server.getURL()));
}
代码示例来源: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: io.micronaut/micronaut-inject
@SuppressWarnings("unchecked")
@Override
default T stop() {
ApplicationContext applicationContext = getApplicationContext();
if (applicationContext != null && applicationContext.isRunning()) {
applicationContext.stop();
}
return (T) this;
}
}
代码示例来源: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: io.micronaut/runtime
applicationContext.start();
Optional<EmbeddedApplication> embeddedContainerBean = applicationContext.findBean(EmbeddedApplication.class);
handleStartupException(applicationContext.getEnvironment(), e);
handleStartupException(applicationContext.getEnvironment(), e);
return null;
代码示例来源:origin: micronaut-projects/micronaut-core
private void stopInternal() {
try {
workerGroup.shutdownGracefully()
.addListener(this::logShutdownErrorIfNecessary);
parentGroup.shutdownGracefully()
.addListener(this::logShutdownErrorIfNecessary);
webSocketSessions.close();
applicationContext.publishEvent(new ServerShutdownEvent(this));
if (serviceInstance != null) {
applicationContext.publishEvent(new ServiceShutdownEvent(serviceInstance));
}
if (applicationContext.isRunning()) {
applicationContext.stop();
}
} catch (Throwable e) {
if (LOG.isErrorEnabled()) {
LOG.error("Error stopping Micronaut server: " + e.getMessage(), e);
}
}
}
代码示例来源:origin: io.micronaut/micronaut-inject
/**
* Run the {@link ApplicationContext}. This method will instantiate a new {@link ApplicationContext} and
* call {@link #start()}.
*
* @return The running {@link ApplicationContext}
*/
static ApplicationContext run() {
return run(StringUtils.EMPTY_STRING_ARRAY);
}
代码示例来源: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: 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/micronaut-management
private void stopServer() {
try {
Thread.sleep(WAIT_BEFORE_STOP);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
this.context.stop();
}
}
代码示例来源: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: 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
/**
* @param context A platform specific context object
* @return Build the {@link ApplicationContext} to use
*/
protected ApplicationContext buildApplicationContext(@Nullable C context) {
if (applicationContext == null) {
final ApplicationContextBuilder contextBuilder = newApplicationContextBuilder();
final Package pkg = getClass().getPackage();
if (pkg != null) {
final String name = pkg.getName();
if (StringUtils.isNotEmpty(name)) {
contextBuilder.packages(name);
}
}
applicationContext = contextBuilder.build();
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
if (applicationContext != null && applicationContext.isRunning()) {
applicationContext.close();
applicationContext = null;
}
}));
}
return applicationContext;
}
代码示例来源:origin: io.micronaut/micronaut-inject
/**
* Starts the {@link ApplicationContext}.
*
* @return The running {@link ApplicationContext}
*/
default ApplicationContext start() {
return build().start();
}
内容来源于网络,如有侵权,请联系作者删除!