Maintainers
Pricing
Enterprise
More
More
Documentation
Try Live
Rankings
Install
Blog
Docs7
Ask
New
Add Docs
Micronaut
https://docs.micronaut.io/5.2.x/
Admin
Micronaut is a modern, JVM-based full-stack framework designed for building modular,
...
Tokens:
1,156,901
Snippets:
7,337
Trust Score:
10
Update:
1 week ago
Context
Chat
Benchmark
56.44
Latest
Show doc for...
Code
Info
Show Results
Tokens:
Raw
Copy
Link
Tokens:
Raw
Copy
Link
### Create bucket with ObjectStorageRxClient (Java) Source: https://docs.micronaut.io/5.2.x/oracle-cloud Java example of creating a bucket using the reactive ObjectStorageRxClient. It first gets the namespace, then creates the bucket and returns its location. ```java @Post(value = "/buckets/{name}") public String createBucket(@PathVariable String name) { String tenancyId = tenancyIdProvider.getTenancyId(); GetNamespaceRequest getNamespaceRequest = GetNamespaceRequest.builder() .compartmentId(tenancyId).build(); String namespace = objectStorage.getNamespace(getNamespaceRequest).getValue(); // __ CreateBucketRequest createBucketRequest = CreateBucketRequest.builder() .namespaceName(namespace) .createBucketDetails(CreateBucketDetails.builder() .compartmentId(tenancyId) .name(name) .build()) .build(); return objectStorage.createBucket(createBucketRequest) // __ .getLocation(); // __ } ``` -------------------------------- ### ChannelPoolListener with ChannelInitializer for queue and exchange setup Source: https://docs.micronaut.io/5.2.x/rabbitmq The imports and the ChannelPoolListener class are shown together as one example. The class extends ChannelInitializer and overrides initialize to declare a priority queue and set up a headers exchange with two queues bound using header arguments. The class must be a singleton to be registered with the context. ```groovy import com.rabbitmq.client.Channel import io.micronaut.rabbitmq.connect.ChannelInitializer import jakarta.inject.Singleton ``` ```groovy @Singleton // __ class ChannelPoolListener extends ChannelInitializer { // __ @Override void initialize(Channel channel, String name) throws IOException { // __ channel.queueDeclare("product", false, false, false, ["x-max-priority": 100]) // __ //docs/exchange channel.exchangeDeclare("animals", "headers", false) channel.queueDeclare("snakes", false, false, false, null) channel.queueDeclare("cats", false, false, false, null) Map<String, Object> catArgs = [:] catArgs.put("x-match", "all") catArgs.put("animalType", "Cat") channel.queueBind("cats", "animals", "", catArgs) Map<String, Object> snakeArgs = [:] snakeArgs.put("x-match", "all") snakeArgs.put("animalType", "Snake") channel.queueBind("snakes", "animals", "", snakeArgs) } } ``` -------------------------------- ### Python: Get pods with CoreV1Api Source: https://docs.micronaut.io/5.2.x/kubernetes Python example showing a GET endpoint that lists pods in a namespace and returns a map of pod names to their status phases. Uses the CoreV1Api's listNamespacedPod method. ```python @Get("/{namespace}") def get_pods(self, namespace: Annotated[str, NotNull]) -> dict[str, str]: v1_pod_list = self.core_v1_api.listNamespacedPod(namespace, None, None, None, None, None, None, None, None, None, None, None, None) return { p.getMetadata().getName(): p.getStatus().getPhase() for p in v1_pod_list.getItems() if p.getStatus() is not None } ``` -------------------------------- ### AppOptics reporter configuration Source: https://docs.micronaut.io/5.2.x/micrometer Configuration examples for the AppOptics reporter in Properties, YAML, and TOML formats. The TOML example is incomplete in the source. ```properties micronaut.metrics.enabled=true micronaut.metrics.export.appoptics.enabled=true micronaut.metrics.export.appoptics.apiToken=${APPOPTICS_API_TOKEN} micronaut.metrics.export.appoptics.uri=https://api.appoptics.com/v1/measurements micronaut.metrics.export.appoptics.step=PT1M ``` ```yaml micronaut: metrics: enabled: true export: appoptics: enabled: true apiToken: ${APPOPTICS_API_TOKEN} uri: https://api.appoptics.com/v1/measurements step: PT1M ``` ```toml [micronaut.metrics] enabled = true ``` -------------------------------- ### Type pollution test with ThresholdFocusListener Source: https://docs.micronaut.io/5.2.x/test Test setup for type pollution detection using micronaut-test-type-pollution. Installs the agent, sets up a ThresholdFocusListener, runs the code under test, and verifies the threshold is not exceeded. The example uses a THRESHOLD of 10_000 and a loop that performs instanceof checks against two interfaces. ```java private static final int THRESHOLD = 10_000; private ThresholdFocusListener focusListener; @BeforeAll static void setupAgent() { TypePollutionTransformer.install(net.bytebuddy.agent.ByteBuddyAgent.install()); // __ } @BeforeEach void setUp() { focusListener = new ThresholdFocusListener(); // __ FocusListener.setFocusListener(focusListener); } @AfterEach void verifyNoTypeThrashing() { FocusListener.setFocusListener(null); // __ Assertions.assertTrue(focusListener.checkThresholds(THRESHOLD), "Threshold exceeded, check logs."); } @Test public void sample() { // __ Object c = new Concrete(); int j = 0; for (int i = 0; i < THRESHOLD * 2; i++) { if (c instanceof A) { j++; } if (c instanceof B) { j++; } } System.out.println(j); } interface A { // __ } interface B { } static class Concrete implements A, B { } ``` -------------------------------- ### Java Pub/Sub client publishing to multiple projects Source: https://docs.micronaut.io/5.2.x/gcp Java example showing how to publish to the default project using a simple topic name and to a different project using a fully qualified topic name. The FQN format is projects/$PROJECT_ID/topics/$TOPIC_NAME. Ensure the service account has access to the other project. ```java import io.micronaut.gcp.pubsub.annotation.PubSubClient; import io.micronaut.gcp.pubsub.annotation.Topic; import io.micronaut.gcp.pubsub.support.Animal; ``` ```java @PubSubClient public interface MultipleProjectClient { @Topic("animals") void sendUS(Animal animal); // __ @Topic("projects/eu-project/topics/animals") void sendEU(Animal animal); // __ } ``` -------------------------------- ### Start EmbeddedServer in Spock with @Shared and @AutoCleanup Source: https://docs.micronaut.io/5.2.x/test Use this Spock test setup to start an EmbeddedServer once for all methods in a class. The @Shared field ensures the server starts only once, and @AutoCleanup shuts it down after the test suite completes. ```Groovy @Shared // __ @AutoCleanup // __ EmbeddedServer embeddedServer = ApplicationContext.run(EmbeddedServer) ``` -------------------------------- ### Create gRPC application with mn CLI Source: https://docs.micronaut.io/5.2.x/grpc Use the Micronaut CLI to create a new application named 'helloworld' for manual gRPC setup. ```bash $ mn create-app helloworld ``` -------------------------------- ### Example JSON Feed response Source: https://docs.micronaut.io/5.2.x/rss Example JSON payload returned by a GET request to /feeds/json. Shows the structure with version, title, home_page_url, feed_url, authors, and items. ```json { "version": "https://jsonfeed.org/version/1.1", "title": "My Example Feed", "home_page_url": "https://example.org/", "feed_url": "https://example.org/feed.json", "authors": [ { "name": "Feed Author", "url": "mailto:feed@example.org" } ], "items": [ { "id": "2", "content_text": "This is a second item.", "authors": [ { "name": "Item Author" } ], "url": "https://example.org/second-item" }, { "id": "1", "content_html": "<p>Hello, world!</p>", "url": "https://example.org/initial-post" } ] } ``` -------------------------------- ### Kotlin OpenTelemetryBuilderCustomizer example (partial) Source: https://docs.micronaut.io/5.2.x/tracing Kotlin version of the OpenTelemetryBuilderCustomizer example, showing the imports and the start of the factory class with the histogram boundaries. The snippet is incomplete in the source; the full customizer method is not shown. ```kotlin import io.micronaut.context.annotation.Factory import io.micronaut.tracing.opentelemetry.OpenTelemetryBuilderCustomizer import io.opentelemetry.sdk.metrics.Aggregation import io.opentelemetry.sdk.metrics.InstrumentSelector import io.opentelemetry.sdk.metrics.InstrumentType import io.opentelemetry.sdk.metrics.View import jakarta.inject.Singleton ``` ```kotlin @Factory class OpenTelemetryBuilderCustomizerExample { private val histogramBoundaries = listOf(1.0, 5.0, 10.0) ``` -------------------------------- ### Starting Consul with Docker Source: https://docs.micronaut.io/5.2.x/discovery-client Starts a local Consul instance using Docker, mapping port 8500 so the Micronaut application can connect to it. Useful as a quick way to get Consul running for development or testing. ```bash docker run -p 8500:8500 consul ``` -------------------------------- ### Enable Info endpoint and configure info.app values Source: https://docs.micronaut.io/5.2.x/control-panel Enable the Info endpoint and expose configuration-backed info.* values. Configure only in environments where the Control Panel should be available, e.g., application-dev.yml or application-test.yml. ```properties endpoints.info.enabled=true info.app.name=my-service info.app.version=1.0.0 ``` ```yaml endpoints: info: enabled: true info: app: name: my-service version: 1.0.0 ``` ```toml [endpoints.info] enabled = true [info.app] name = "my-service" version = "1.0.0" ``` ```groovy endpoints { info { enabled = true } } info { app { name = 'my-service' version = '1.0.0' } } ``` ```hocon { endpoints = { info = { enabled = true } } info = { app = { name = "my-service" version = "1.0.0" } } } ``` ```json { "endpoints": { "info": { "enabled": true } }, "info": { "app": { "name": "my-service", "version": "1.0.0" } } } ``` -------------------------------- ### Import Micronaut Security Annotations Source: https://docs.micronaut.io/5.2.x/security Imports required Micronaut HTTP and security annotations for the controller example. These imports are needed for the @Controller, @Get, @Produces, @PermitAll, and @RolesAllowed annotations used in the example controller. ```java import io.micronaut.http.MediaType import io.micronaut.http.annotation.Controller import io.micronaut.http.annotation.Get import io.micronaut.http.annotation.Produces import jakarta.annotation.security.PermitAll import jakarta.annotation.security.RolesAllowed ``` -------------------------------- ### Python Pub/Sub client publishing to multiple projects Source: https://docs.micronaut.io/5.2.x/gcp Python example showing how to publish to the default project using a simple topic name and to a different project using a fully qualified topic name. The FQN format is projects/$PROJECT_ID/topics/$TOPIC_NAME. Ensure the service account has access to the other project. ```python from micronaut.gcp.pubsub.annotation import PubSubClient, Topic from micronaut.gcp.pubsub.support.Animal import Animal ``` ```python @PubSubClient class MultipleProjectClient(ABC): @Topic("animals") @abstractmethod def send_us(self, animal: Animal) -> None: # __ ... @Topic("projects/eu-project/topics/animals") @abstractmethod def send_eu(self, animal: Animal) -> None: # __ ... ``` -------------------------------- ### Use CoreV1ApiReactorClient in Python Source: https://docs.micronaut.io/5.2.x/kubernetes Python equivalent of the Reactor client example. Inject CoreV1ApiReactorClient and call listNamespacedPod(namespace).execute() to get a V1PodList. ```python from jakarta.inject import Singleton from micronaut.kubernetes.client.reactor import CoreV1ApiReactorClient ``` ```python @Singleton class MyService: def __init__(self, core_v1_api_reactor_client: CoreV1ApiReactorClient): self.core_v1_api_reactor_client = core_v1_api_reactor_client def my_method(self, namespace: str) -> None: v1_pod_list = self.core_v1_api_reactor_client.listNamespacedPod(namespace).execute() ``` -------------------------------- ### Create bucket with ObjectStorageRxClient (Groovy) Source: https://docs.micronaut.io/5.2.x/oracle-cloud Groovy example using reactive composition with flatMap. It sends a namespace request, then creates a bucket and returns its location as a Mono. ```groovy @Override @Post(value = '/buckets/{name}') Mono<String> createBucket(String name) { String tenancyId = tenancyIdProvider.tenancyId GetNamespaceRequest getNamespaceRequest = GetNamespaceRequest.builder() .compartmentId(tenancyId).build() return objectStorage.getNamespace(getNamespaceRequest) // __ .flatMap(namespaceResponse -> { CreateBucketRequest createBucketRequest = CreateBucketRequest.builder() .namespaceName(namespaceResponse.value) .createBucketDetails(CreateBucketDetails.builder() .compartmentId(tenancyId) .name(name) .build()) .build() return objectStorage.createBucket(createBucketRequest) // __ .map(CreateBucketResponse::getLocation) // __ }) as Mono<String> } ``` -------------------------------- ### Start application with startApplication extension Source: https://docs.micronaut.io/5.2.x/kotlin Example application using the startApplication extension function. Configures packages and maps RuntimeException to HTTP 500. ```Kotlin object Application fun main(args: Array<String>) { startApplication<Application>(*args) { packages("org.example.app") mapError<RuntimeException> { 500 } } } ``` -------------------------------- ### Create application with mn CLI and graphql feature Source: https://docs.micronaut.io/5.2.x/graphql Creates a new Micronaut application named helloworld with the graphql feature using the Command Line tool. ```text mn create-app helloworld --features=graphql ``` -------------------------------- ### Use CoreV1ApiReactorClient in Groovy Source: https://docs.micronaut.io/5.2.x/kubernetes Groovy version of the Reactor client example. Inject CoreV1ApiReactorClient and call listNamespacedPod(namespace).execute() to get a Mono<V1PodList>. ```groovy import io.kubernetes.client.openapi.models.V1PodList import io.micronaut.kubernetes.client.reactor.CoreV1ApiReactorClient import jakarta.inject.Singleton import reactor.core.publisher.Mono ``` ```groovy @Singleton class MyService { private final CoreV1ApiReactorClient coreV1ApiReactorClient MyService(CoreV1ApiReactorClient coreV1ApiReactorClient) { this.coreV1ApiReactorClient = coreV1ApiReactorClient } void myMethod(String namespace) { Mono<V1PodList> v1PodList = coreV1ApiReactorClient.listNamespacedPod(namespace).execute() } } ``` -------------------------------- ### Kotlin Pub/Sub client publishing to multiple projects Source: https://docs.micronaut.io/5.2.x/gcp Kotlin example showing how to publish to the default project using a simple topic name and to a different project using a fully qualified topic name. The FQN format is projects/$PROJECT_ID/topics/$TOPIC_NAME. Ensure the service account has access to the other project. ```kotlin import io.micronaut.gcp.pubsub.annotation.PubSubClient import io.micronaut.gcp.pubsub.annotation.Topic import io.micronaut.gcp.pubsub.support.Animal ``` ```kotlin @PubSubClient interface MultipleProjectClient { @Topic("animals") fun sendUS(animal: Animal) // __ @Topic("projects/eu-project/topics/animals") fun sendEU(animal: Animal) // __ } ``` -------------------------------- ### Define gRPC Service in helloworld.proto Source: https://docs.micronaut.io/5.2.x/grpc Define a gRPC service in a protobuf file. This example defines the Greeter service with a SayHello RPC and the HelloRequest/HelloReply messages. Place it in src/main/proto/helloworld.proto. With Micronaut 1.1+ CLI, you can generate a service using mn create-grpc-service helloworld which creates the proto file and the implementing class. ```Protobuf // Copyright 2015 The gRPC Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. syntax = "proto3"; option java_multiple_files = true; option java_package = "helloworld"; option java_outer_classname = "HelloWorldProto"; option objc_class_prefix = "HLW"; package helloworld; // The greeting service definition. service Greeter { // Sends a greeting rpc SayHello (HelloRequest) returns (HelloReply) {} } // The request message containing the user's name. message HelloRequest { string name = 1; } // The response message containing the greetings message HelloReply { string message = 1; } ``` -------------------------------- ### Use CoreV1ApiReactorClient in Kotlin Source: https://docs.micronaut.io/5.2.x/kubernetes Kotlin version of the Reactor client example. Inject CoreV1ApiReactorClient and call listNamespacedPod(namespace).execute() to get a Mono<V1PodList>. ```kotlin import io.kubernetes.client.openapi.models.V1PodList import io.micronaut.kubernetes.client.reactor.CoreV1ApiReactorClient import jakarta.inject.Singleton import reactor.core.publisher.Mono ``` ```kotlin @Singleton class MyService(private val coreV1ApiReactorClient: CoreV1ApiReactorClient) { fun myMethod(namespace: String) { val v1PodList: Mono<V1PodList> = coreV1ApiReactorClient.listNamespacedPod(namespace).execute() } } ``` -------------------------------- ### Configure JetStream KeyValue Store Source: https://docs.micronaut.io/5.2.x/nats Configuration for a JetStream key/value store named 'examplebucket' with storage type Memory and max history per key 5. Available in Properties, YAML, TOML, Groovy, HOCON, and JSON formats. ```properties nats.default.jetstream.keyvalue.examplebucket.storage-type=Memory nats.default.jetstream.keyvalue.examplebucket.max-history-per-key=5 ``` ```yaml nats: default: jetstream: keyvalue: examplebucket: storage-type: Memory max-history-per-key: 5 ``` ```toml [nats.default.jetstream.keyvalue.examplebucket] storage-type = "Memory" max-history-per-key = 5 ``` ```groovy nats { 'default' { jetstream { keyvalue { examplebucket { storageType = 'Memory' maxHistoryPerKey = 5 } } } } } ``` ```hocon { nats = { default = { jetstream = { keyvalue = { examplebucket = { storage-type = "Memory" max-history-per-key = 5 } } } } } } ``` ```json { "nats": { "default": { "jetstream": { "keyvalue": { "examplebucket": { "storage-type": "Memory", "max-history-per-key": 5 } } } } } } ``` -------------------------------- ### Postgres storage target configuration Source: https://docs.micronaut.io/5.2.x/eclipsestore Configuration for using Postgres as a storage target requires a Postgres JDBC datasource. Add the required dependencies to get started. ```text 1. You can also inject an instance of RootProvider to easily access the EclipseStore Root Instance. If your Micronaut application has only a single EclipseStore Instance, you don’t need to specify a name qualifier to inject it. 2. The rule is: "The Object that has been modified has to be stored!". 3. To store a newly created object, store the "owner" of the object. ``` -------------------------------- ### Configure OpenTelemetry propagators with X-Ray (Properties) Source: https://docs.micronaut.io/5.2.x/tracing Configuration file example setting the OTLP exporter and propagators to include 'xray'. ```properties otel.traces.exporter=otlp otel.propagators=tracecontext, baggage, xray ``` -------------------------------- ### Add micronaut-cache-core dependency with Gradle Source: https://docs.micronaut.io/5.2.x/cache Declare the micronaut-cache-core dependency in a Gradle build to get started with the cache implementations. Requires at least Micronaut version 1.3.0. ```groovy implementation("io.micronaut.cache:micronaut-cache-core") ``` -------------------------------- ### Example application.conf for config4k Source: https://docs.micronaut.io/5.2.x/kotlin An example HOCON configuration file using the .conf extension. It sets the server port to 8081, defines a test-property, and references the USER environment variable. ```hocon micronaut { server { port = 8081 } } test-property = "bad-value" custom { user = ${USER} } ``` -------------------------------- ### Configure a container with image, ports, env, labels, and timeout Source: https://docs.micronaut.io/5.2.x/test-resources Configure a container named 'mycontainer' with image, hostnames, exposed ports, command, environment variables, labels, and startup timeout. The TOML block shows how to set a label array element. The Groovy, HOCON, and JSON blocks show equivalent configuration in different formats. ```TOML [[test-resources.containers.mycontainer.labels]] "my.label" = "my value" ``` ```Groovy testResources { containers { mycontainer { imageName = 'my/container' hostnames = ['my.service.host'] exposedPorts = ['[object Object]'] command = 'some.sh' env = ['[object Object]'] labels = ['[object Object]'] startupTimeout = '120s' } } } ``` ```HOCON { test-resources = { containers = { mycontainer = { image-name = "my/container" hostnames = ["my.service.host"] exposed-ports = [{ my.service.port = 1883 }] command = "some.sh" env = [{ MY_ENV_VAR = "my value" }] labels = [{ my.label = "my value" }] startup-timeout = "120s" } } } } ``` ```JSON { "test-resources": { "containers": { "mycontainer": { "image-name": "my/container", "hostnames": [ "my.service.host" ], "exposed-ports": [ { "my.service.port": 1883 } ], "command": "some.sh", "env": [ { "MY_ENV_VAR": "my value" } ], "labels": [ { "my.label": "my value" } ], "startup-timeout": "120s" } } } } ``` -------------------------------- ### Get Existing SharedIndexInformer in Groovy Source: https://docs.micronaut.io/5.2.x/kubernetes Groovy example of retrieving an existing SharedIndexInformer for V1ConfigMap using the SharedIndexInformerFactory bean's getExistingSharedIndexInformer method. The method takes the class and namespace as arguments. ```groovy SharedIndexInformer<V1ConfigMap> informer = sharedIndexInformerFactory.getExistingSharedIndexInformer( V1ConfigMap, namespace) ``` -------------------------------- ### Groovy Pub/Sub client publishing to multiple projects Source: https://docs.micronaut.io/5.2.x/gcp Groovy example showing how to publish to the default project using a simple topic name and to a different project using a fully qualified topic name. The FQN format is projects/$PROJECT_ID/topics/$TOPIC_NAME. Ensure the service account has access to the other project. ```groovy import io.micronaut.gcp.pubsub.annotation.PubSubClient; import io.micronaut.gcp.pubsub.annotation.Topic; import io.micronaut.gcp.pubsub.support.Animal; ``` ```groovy @PubSubClient interface MultipleProjectClient { @Topic("animals") void sendUS(Animal animal) // __ @Topic("projects/eu-project/topics/animals") void sendEU(Animal animal) // __ } ``` -------------------------------- ### Get Existing SharedIndexInformer in Kotlin Source: https://docs.micronaut.io/5.2.x/kubernetes Kotlin example of retrieving an existing SharedIndexInformer for V1ConfigMap using the SharedIndexInformerFactory bean's getExistingSharedIndexInformer method. The method takes the class and namespace as arguments. ```kotlin val informer = sharedIndexInformerFactory.getExistingSharedIndexInformer( V1ConfigMap::class.java, namespace) ``` -------------------------------- ### Configure OpenTelemetry propagators with X-Ray (Groovy) Source: https://docs.micronaut.io/5.2.x/tracing Configuration file example setting the OTLP exporter and propagators to include 'xray'. ```groovy otel { traces { exporter = 'otlp' } propagators = 'tracecontext, baggage, xray' } ``` -------------------------------- ### Get Existing SharedIndexInformer in Python Source: https://docs.micronaut.io/5.2.x/kubernetes Python example of retrieving an existing SharedIndexInformer for V1ConfigMap using the SharedIndexInformerFactory bean's getExistingSharedIndexInformer method. The method takes the class and namespace as arguments. ```python informer = self.shared_index_informer_factory.getExistingSharedIndexInformer( V1ConfigMap, namespace) ``` -------------------------------- ### Create a Picocli project with http-client feature Source: https://docs.micronaut.io/5.2.x/picocli Creates a new Micronaut CLI application with picocli support and the http-client feature, used for the GitHub API example. ```bash $ mn create-cli-app example.git-star --features http-client ``` -------------------------------- ### Get Existing SharedIndexInformer in Java Source: https://docs.micronaut.io/5.2.x/kubernetes Java example of retrieving an existing SharedIndexInformer for V1ConfigMap using the SharedIndexInformerFactory bean's getExistingSharedIndexInformer method. The method takes the class and namespace as arguments. ```java SharedIndexInformer<V1ConfigMap> informer = sharedIndexInformerFactory.getExistingSharedIndexInformer( V1ConfigMap.class, namespace); ``` -------------------------------- ### Configure generic container with file system bindings (Properties, YAML, TOML, Groovy, HOCON, JSON) Source: https://docs.micronaut.io/5.2.x/test-resources Configures a generic test container with file system bindings (read-only and read-write) in six formats: Properties, YAML, TOML, Groovy, HOCON, and JSON. The container is named 'mycontainer' and exposes port 1883 for 'my.service.port'. The 'ro-fs-bind' and 'rw-fs-bind' keys map host files to container paths. ```properties test-resources.containers.mycontainer.image-name=my/container test-resources.containers.mycontainer.hostnames[0]=my.service.host test-resources.containers.mycontainer.exposed-ports[0].my.service.port=1883 test-resources.containers.mycontainer.ro-fs-bind[0].readonly-file.conf=/path/to/container/readonly-file.conf test-resources.containers.mycontainer.rw-fs-bind[0].readwrite-file.conf=/path/to/container/readwrite-file.conf ``` ```yaml test-resources: containers: mycontainer: image-name: my/container hostnames: - my.service.host exposed-ports: - my.service.port: 1883 ro-fs-bind: - "readonly-file.conf": /path/to/container/readonly-file.conf rw-fs-bind: - "readwrite-file.conf": /path/to/container/readwrite-file.conf ``` ```toml [test-resources.containers.mycontainer] image-name = "my/container" hostnames = [ "my.service.host" ] [[test-resources.containers.mycontainer.exposed-ports]] "my.service.port" = 1883 [[test-resources.containers.mycontainer.ro-fs-bind]] "readonly-file.conf" = "/path/to/container/readonly-file.conf" [[test-resources.containers.mycontainer.rw-fs-bind]] "readwrite-file.conf" = "/path/to/container/readwrite-file.conf" ``` ```groovy testResources { containers { mycontainer { imageName = 'my/container' hostnames = ['my.service.host'] exposedPorts = ['[object Object]'] roFsBind = ['[object Object]'] rwFsBind = ['[object Object]'] } } } ``` ```hocon { test-resources = { containers = { mycontainer = { image-name = "my/container" hostnames = ["my.service.host"] exposed-ports = [{ my.service.port = 1883 }] ro-fs-bind = [{ readonly-file.conf = "/path/to/container/readonly-file.conf" }] rw-fs-bind = [{ readwrite-file.conf = "/path/to/container/readwrite-file.conf" }] } } } } ``` ```json { "test-resources": { "containers": { "mycontainer": { "image-name": "my/container", "hostnames": [ "my.service.host" ], "exposed-ports": [ { "my.service.port": 1883 } ], "ro-fs-bind": [ { "readonly-file.conf": "/path/to/container/readonly-file.conf" } ], "rw-fs-bind": [ { "readwrite-file.conf": "/path/to/container/readwrite-file.conf" } ] } } } } ``` -------------------------------- ### Generated code for EL expression evaluation Source: https://docs.micronaut.io/5.2.x/jakarta-el Shows the Java code generated by the annotation processor for the Quick Start example. It demonstrates how the processor parses the expression once, resolves variables, and calls getters directly for efficient evaluation. ```java @ELEnvironment(variables = @ELVariable(name = "book", type = Book.class)) @ELExpression("Book: ${book.title} costs ${book.unitPrice}") protected Object evaluate(ELContext context) { Book shared0 = (Book) ELResolution.resolveVariable(context, "book"); return "Book: " + Objects.toString(shared0.getTitle(), "") + " costs " + String.valueOf(shared0.getUnitPrice()); } ``` -------------------------------- ### Python Pub/Sub listener with @Subscription simple and FQN names Source: https://docs.micronaut.io/5.2.x/gcp Python example showing a Pub/Sub listener with @PubSubListener and @Subscription annotations. The first subscription uses a simple name 'animals' and the second uses a fully qualified name (FQN) 'projects/eu-project/subscriptions/animals' to listen to a subscription in a different project. ```python from micronaut.context.annotation import Requires from micronaut.gcp.pubsub.annotation import PubSubListener, Subscription from micronaut.gcp.pubsub.support.Animal import Animal ``` ```python @PubSubListener # __ class SimpleSubscriber: @Subscription("animals") # __ def on_message(self, animal: Animal) -> None: ... @Subscription("projects/eu-project/subscriptions/animals") # __ def on_message_eu(self, animal: Animal) -> None: ... ``` -------------------------------- ### Using Trace Annotations in Groovy Source: https://docs.micronaut.io/5.2.x/tracing Example of using @NewSpan, @ContinueSpan, and @SpanTag annotations in a Groovy service. The @NewSpan annotation starts a new span, @SpanTag includes method arguments as tags, and @ContinueSpan continues an existing span. ```groovy import io.micronaut.tracing.annotation.ContinueSpan import io.micronaut.tracing.annotation.NewSpan import io.micronaut.tracing.annotation.SpanTag import jakarta.inject.Singleton ``` ```groovy @Singleton class HelloService { @NewSpan("hello-world") // __ String hello(@SpanTag("person.name") String name) { // __ return greet("Hello " + name) } @ContinueSpan // __ String greet(@SpanTag("hello.greeting") String greet) { return greet } } ``` -------------------------------- ### Using Trace Annotations in Kotlin Source: https://docs.micronaut.io/5.2.x/tracing Example of using @NewSpan, @ContinueSpan, and @SpanTag annotations in a Kotlin service. The @NewSpan annotation starts a new span, @SpanTag includes method arguments as tags, and @ContinueSpan continues an existing span. ```kotlin import io.micronaut.tracing.annotation.ContinueSpan import io.micronaut.tracing.annotation.NewSpan import io.micronaut.tracing.annotation.SpanTag import jakarta.inject.Singleton ``` ```kotlin @Singleton open class HelloService { @NewSpan("hello-world") // __ open fun hello(@SpanTag("person.name") name: String): String { // __ return greet("Hello $name") } @ContinueSpan // __ open fun greet(@SpanTag("hello.greeting") greet: String): String { return greet } } ``` -------------------------------- ### Create Pub/Sub emulator topic with curl Source: https://docs.micronaut.io/5.2.x/gcp Create a topic named 'micronaut-devices' on the 'test-project' project using the Pub/Sub REST interface. Requires the PUBSUB_EMULATOR_HOST environment variable to be set, and GCP_PROJECT_ID should match the emulator project to avoid picking up the default credentials' projectId. ```bash curl -XPUT $PUBSUB_EMULATOR_HOST/v1/projects/test-project/topics/micronaut-devices ``` -------------------------------- ### Using Trace Annotations in Python Source: https://docs.micronaut.io/5.2.x/tracing Example of using @NewSpan, @ContinueSpan, and @SpanTag annotations in a Python service. The @NewSpan annotation starts a new span, @SpanTag includes method arguments as tags, and @ContinueSpan continues an existing span. ```python from typing import Annotated from jakarta.inject import Singleton from micronaut.tracing.annotation import ContinueSpan, NewSpan, SpanTag ``` ```python @Singleton class HelloService: @NewSpan("hello-world") # __ def hello(self, name: Annotated[str, SpanTag("person.name")]) -> str: # __ return self.greet("Hello " + name) @ContinueSpan # __ def greet(self, greet: Annotated[str, SpanTag("hello.greeting")]) -> str: return greet ``` -------------------------------- ### Groovy Pub/Sub listener with @Subscription simple and FQN names Source: https://docs.micronaut.io/5.2.x/gcp Groovy example showing a Pub/Sub listener with @PubSubListener and @Subscription annotations. The first subscription uses a simple name 'animals' and the second uses a fully qualified name (FQN) 'projects/eu-project/subscriptions/animals' to listen to a subscription in a different project. ```groovy import io.micronaut.gcp.pubsub.annotation.PubSubListener import io.micronaut.gcp.pubsub.annotation.Subscription import io.micronaut.gcp.pubsub.support.Animal ``` ```groovy @PubSubListener // __ class SimpleSubscriber { @Subscription("animals") // __ void onMessage(Animal animal) { } @Subscription("projects/eu-project/subscriptions/animals") // __ void onMessageEU(Animal animal) { } } ``` -------------------------------- ### Using Trace Annotations in Java Source: https://docs.micronaut.io/5.2.x/tracing Example of using @NewSpan, @ContinueSpan, and @SpanTag annotations in a Java service. The @NewSpan annotation starts a new span, @SpanTag includes method arguments as tags, and @ContinueSpan continues an existing span. ```java import io.micronaut.tracing.annotation.ContinueSpan; import io.micronaut.tracing.annotation.NewSpan; import io.micronaut.tracing.annotation.SpanTag; import jakarta.inject.Singleton; ``` ```java @Singleton class HelloService { @NewSpan("hello-world") // __ public String hello(@SpanTag("person.name") String name) { // __ return greet("Hello " + name); } @ContinueSpan // __ public String greet(@SpanTag("hello.greeting") String greet) { return greet; } } ``` -------------------------------- ### Example New Relic Telemetry config (Properties/YAML) Source: https://docs.micronaut.io/5.2.x/micrometer Example New Relic Telemetry configuration in Properties and YAML. Sets enabled, apiKey, serviceName, and step. The apiKey is required. ```properties micronaut.metrics.enabled=true micronaut.metrics.export.newrelic.enabled=true micronaut.metrics.export.newrelic.apiKey=${NEWRELIC_API_KEY} micronaut.metrics.export.newrelic.serviceName=My Micronaut Service micronaut.metrics.export.newrelic.step=PT1M ``` ```yaml micronaut: metrics: enabled: true export: newrelic: enabled: true apiKey: ${NEWRELIC_API_KEY} serviceName: My Micronaut Service step: PT1M ``` -------------------------------- ### Content negotiation test request with accept header Source: https://docs.micronaut.io/5.2.x/aws Example test call that sends an HTTP GET request with an Accept header for text/plain. If the server route does not declare @Produces("text/plain"), the request won't match. ```java String result = client.toBlocking().retrieve( HttpRequest.GET("/test") .accept("text/plain"), String) ``` -------------------------------- ### Access SharedIndexInformer local cache with getIndexer() Source: https://docs.micronaut.io/5.2.x/kubernetes Retrieves all V1ConfigMap objects from the SharedIndexInformer's local cache using the getIndexer() method. The cache is eventually consistent with the authoritative state and starts empty. The example is shown in Java, Python, Kotlin, and Groovy. ```java List<V1ConfigMap> all() { String namespace = namespaceResolver.resolveNamespace(); SharedIndexInformer<V1ConfigMap> informer = sharedIndexInformerFactory.getExistingSharedIndexInformer( V1ConfigMap.class, namespace); Indexer<V1ConfigMap> indexer = informer.getIndexer(); return indexer.list(); } ``` ```python def all(self) -> list[V1ConfigMap]: namespace = self.namespace_resolver.resolveNamespace() informer = self.shared_index_informer_factory.getExistingSharedIndexInformer( V1ConfigMap, namespace) indexer = informer.getIndexer() return indexer.list() ``` ```kotlin fun all(): List<V1ConfigMap> { val namespace = namespaceResolver.resolveNamespace() val informer = sharedIndexInformerFactory.getExistingSharedIndexInformer( V1ConfigMap::class.java, namespace) val indexer = informer!!.indexer return indexer.list() } ``` ```groovy List<V1ConfigMap> all() { String namespace = namespaceResolver.resolveNamespace() SharedIndexInformer<V1ConfigMap> informer = sharedIndexInformerFactory.getExistingSharedIndexInformer( V1ConfigMap, namespace) Indexer<V1ConfigMap> indexer = informer.indexer return indexer.list() } ```