### Use Map Configuration (Kotlin) Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/index.html Kotlin example that runs an ApplicationContext with a map of properties and prints the vehicle start message. ```kotlin val subMap = mapOf( 0 to "thermostat", 1 to "fuel pressure" ) val map = mapOf( "my.engine.cylinders" to "8", "my.engine.sensors" to subMap ) val applicationContext = ApplicationContext.run(map, "test") val vehicle = applicationContext.getBean(Vehicle::class.java) println(vehicle.start()) ``` -------------------------------- ### Use Map Configuration (Java) Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/index.html Java example that builds a map of properties and runs an ApplicationContext, then prints the vehicle start message. ```java Map map = new LinkedHashMap<>(2); map.put("my.engine.cylinders", "8"); Map map1 = new LinkedHashMap<>(2); map1.put(0, "thermostat"); map1.put(1, "fuel pressure"); map.put("my.engine.sensors", map1); ApplicationContext applicationContext = ApplicationContext.run(map, "test"); Vehicle vehicle = applicationContext.getBean(Vehicle.class); System.out.println(vehicle.start()); ``` -------------------------------- ### Use Map Configuration (Groovy) Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/index.html Groovy example that runs an ApplicationContext with a map of properties and prints the vehicle start message. ```groovy ApplicationContext applicationContext = ApplicationContext.run( ['my.engine.cylinders': '8', 'my.engine.sensors' : [0: 'thermostat', 1: 'fuel pressure']], "test" ) def vehicle = applicationContext.getBean(Vehicle) println(vehicle.start()) ``` -------------------------------- ### Supply Configuration in Java Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/index.html Shows how to supply configuration values to the ApplicationContext in Java using a Map of properties and the 'test' environment. The example then retrieves a Vehicle bean and prints its start() result. ```java Map properties = new HashMap<>(); properties.put("my.engine.cylinders" ,"4"); properties.put("my.engine.manufacturer" , "Subaru"); properties.put("my.engine.crank-shaft.rod-length", 4); properties.put("my.engine.spark-plug.name" , "6619 LFR6AIX"); properties.put("my.engine.spark-plug.type" , "Iridium"); properties.put("my.engine.spark-plug.companyName", "NGK"); ApplicationContext applicationContext = ApplicationContext.run(properties, "test"); Vehicle vehicle = applicationContext.getBean(Vehicle.class); System.out.println(vehicle.start()); ``` -------------------------------- ### Run BeanContext and get Vehicle bean (Java) Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/index.html Shows how to start the BeanContext and retrieve the Vehicle bean using getBean(). The example prints the result of vehicle.start(). ```java final BeanContext context = BeanContext.run(); Vehicle vehicle = context.getBean(Vehicle.class); System.out.println(vehicle.start()); ``` -------------------------------- ### Supply Configuration in Kotlin Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/index.html Shows how to supply configuration values to the ApplicationContext in Kotlin using a map and the 'test' environment. The example then retrieves a Vehicle bean and prints its start() result. ```kotlin val applicationContext = ApplicationContext.run( mapOf( "my.engine.cylinders" to "4", "my.engine.manufacturer" to "Subaru", "my.engine.crank-shaft.rod-length" to 4, "my.engine.spark-plug.name" to "6619 LFR6AIX", "my.engine.spark-plug.type" to "Iridium", "my.engine.spark-plug.company" to "NGK" ), "test" ) val vehicle = applicationContext.getBean(Vehicle::class.java) println(vehicle.start()) ``` -------------------------------- ### Supply Configuration in Groovy Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/index.html Shows how to supply configuration values to the ApplicationContext in Groovy using a map literal and the 'test' environment. The example then retrieves a Vehicle bean and prints its start() result. ```groovy ApplicationContext applicationContext = ApplicationContext.run( ['my.engine.cylinders' : '4', 'my.engine.manufacturer' : 'Subaru', 'my.engine.crank-shaft.rod-length': 4, 'my.engine.spark-plug.name' : '6619 LFR6AIX', 'my.engine.spark-plug.type' : 'Iridium', 'my.engine.spark-plug.companyName': 'NGK' ], "test" ) Vehicle vehicle = applicationContext.getBean(Vehicle) println(vehicle.start()) ``` -------------------------------- ### Using BeanProvider with @Any (Java) Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/index.html Example of injecting a BeanProvider with the @Any qualifier to get any available Engine instance. The ifPresent method is used to start the engine if present. ```java import io.micronaut.context.BeanProvider; import io.micronaut.context.annotation.Any; import jakarta.inject.Singleton; @Singleton public class Vehicle { final BeanProvider engineProvider; public Vehicle(@Any BeanProvider engineProvider) { // (1) this.engineProvider = engineProvider; } void start() { engineProvider.ifPresent(Engine::start); // (2) } } ``` -------------------------------- ### Kotlin controller example Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/index.html A simple Micronaut controller written in Kotlin that responds to GET requests with a greeting. ```kotlin package example import io.micronaut.http.annotation.* @Controller("/") class HelloController { @Get("/hello/{name}") fun hello(name: String): String { return "Hello $name" } } ``` -------------------------------- ### Logback configuration example (logback.xml) Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/index.html Example logback.xml configuration with a console appender and root level info. ```xml true %cyan(%d{HH:mm:ss.SSS}) %gray([%thread]) %highlight(%-5level) %magenta(%logger{36}) - %msg%n ``` -------------------------------- ### Programmatically creating Secondary servers (Groovy) Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/index.html Groovy version of the same Factory Bean example. It uses the same approach but with Groovy syntax, including 'def' for local variables and property access for configuration. The server is started and registered as a bean, and its URI is exposed via a ServiceInstanceList. ```groovy import io.micronaut.context.annotation.Bean import io.micronaut.context.annotation.Context import io.micronaut.context.annotation.Factory import io.micronaut.context.annotation.Requires import io.micronaut.context.env.Environment import io.micronaut.core.util.StringUtils import io.micronaut.discovery.ServiceInstanceList import io.micronaut.discovery.StaticServiceInstanceList import io.micronaut.http.server.netty.NettyEmbeddedServer import io.micronaut.http.server.netty.NettyEmbeddedServerFactory import io.micronaut.http.server.netty.configuration.NettyHttpServerConfiguration import io.micronaut.http.ssl.ServerSslConfiguration import jakarta.inject.Named @Factory class SecondaryNettyServer { static final String SERVER_ID = "another" // (1) @Named(SERVER_ID) @Context @Bean(preDestroy = "stop") // (2) @Requires(beans = Environment.class) NettyEmbeddedServer nettyEmbeddedServer(NettyEmbeddedServerFactory serverFactory) { // (3) def configuration = new NettyHttpServerConfiguration() // (4) def sslConfiguration = new ServerSslConfiguration() // (5) sslConfiguration.setBuildSelfSigned(true) sslConfiguration.enabled = true sslConfiguration.port = -1 // random port // configure server programmatically final NettyEmbeddedServer embeddedServer = serverFactory.build(configuration, sslConfiguration) // (5) embeddedServer.start() // (6) return embeddedServer // (7) } @Bean ServiceInstanceList serviceInstanceList( // (8) @Named(SERVER_ID) NettyEmbeddedServer nettyEmbeddedServer) { return new StaticServiceInstanceList( SERVER_ID, [ nettyEmbeddedServer.URI ] ) } } ``` -------------------------------- ### Create application with custom default package Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/index.html Prefix the application name with the desired package to set the default package. For example, 'example.my-demo-app' results in the default package 'example'. ```bash $ mn create-app example.my-demo-app ``` -------------------------------- ### Programmatically creating Secondary servers (Java) Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/index.html Java example of a Factory Bean that starts an additional Netty server using NettyEmbeddedServerFactory. It configures the server programmatically with a self-signed SSL certificate and a random port, then starts it. The server is registered as a bean with the name 'another' and its URI is exposed via a ServiceInstanceList. ```java import java.util.Collections; import io.micronaut.context.annotation.Bean; import io.micronaut.context.annotation.Context; import io.micronaut.context.annotation.Factory; import io.micronaut.context.annotation.Requires; import io.micronaut.context.env.Environment; import io.micronaut.core.util.StringUtils; import io.micronaut.discovery.ServiceInstanceList; import io.micronaut.discovery.StaticServiceInstanceList; import io.micronaut.http.server.netty.NettyEmbeddedServer; import io.micronaut.http.server.netty.NettyEmbeddedServerFactory; import io.micronaut.http.server.netty.configuration.NettyHttpServerConfiguration; import io.micronaut.http.ssl.ServerSslConfiguration; import jakarta.inject.Named; @Factory public class SecondaryNettyServer { public static final String SERVER_ID = "another"; // (1) @Named(SERVER_ID) @Context @Bean(preDestroy = "close") // (2) @Requires(beans = Environment.class) NettyEmbeddedServer nettyEmbeddedServer(NettyEmbeddedServerFactory serverFactory) { // (3) // configure server programmatically final NettyHttpServerConfiguration configuration = new NettyHttpServerConfiguration(); // (4) final ServerSslConfiguration sslConfiguration = new ServerSslConfiguration(); // (5) sslConfiguration.setBuildSelfSigned(true); sslConfiguration.setEnabled(true); sslConfiguration.setPort(-1); // random port final NettyEmbeddedServer embeddedServer = serverFactory.build(configuration, sslConfiguration); // (6) embeddedServer.start(); // (7) return embeddedServer; // (8) } @Bean ServiceInstanceList serviceInstanceList( // (9) @Named(SERVER_ID) NettyEmbeddedServer nettyEmbeddedServer) { return new StaticServiceInstanceList( SERVER_ID, Collections.singleton(nettyEmbeddedServer.getURI()) ); } } ``` -------------------------------- ### BintrayService HTTP client example (Kotlin) Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/index.html Kotlin version of the BintrayService example, using constructor injection with @param:Client and @param:Value annotations. ```kotlin class BintrayApi { public static final String URL = 'https://api.bintray.com' } @Singleton internal class BintrayService( @param:Client(BintrayApi.URL) val client: HttpClient, // (1) @param:Value("\${bintray.organization}") val org: String) { fun fetchRepositories(): Flux> { return Flux.from(client.exchange(HttpRequest.GET("/repos/$org"), String::class.java)) // (2) } fun fetchPackages(repo: String): Flux> { return Flux.from(client.exchange(HttpRequest.GET("/repos/$org/$repo/packages"), String::class.java)) // (2) } } ``` -------------------------------- ### ConfigurationInfoSource example in application.groovy Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/index.html Example configuration for the ConfigurationInfoSource. It sets properties under the 'info' key, including a string, an integer, and a map. The resulting JSON response from the info endpoint is shown. ```groovy info.demo.string = "demo string" info.demo.number = 123 info.demo.map = [key: 'value', other_key: 123] ``` ```json { "demo": { "string": "demo string", "number": 123, "map": { "key": "value", "other_key": 123 } } } ``` -------------------------------- ### micronaut-cli.yml example Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/index.html Example contents of the micronaut-cli.yml file generated by create commands, storing project options and features. ```yaml applicationType: default defaultPackage: com.example testFramework: junit sourceLanguage: java buildTool: gradle features: [annotation-api, app-name, application, gradle, http-client, java, junit, logback, netty-server, shade, yaml] ``` -------------------------------- ### Example application.yml configuration Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/index.html Example configuration file showing nested properties under 'jpa.default.properties' that can be resolved as a flattened map. ```yaml datasources: default: name: 'mydb' jpa: default: properties: hibernate: hbm2ddl: auto: update show_sql: true ``` -------------------------------- ### Start all engines with BeanProvider (Kotlin) Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/index.html Kotlin method to start all engines if any are present, using isPresent and forEach. ```kotlin fun startAll() { if (engineProvider.isPresent) { // (1) engineProvider.forEach { it.start() } // (2) } ``` -------------------------------- ### Basic Jackson configuration example Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/index.html Example YAML configuration showing how to set serializationInclusion to ALWAYS. ```yaml jackson: serializationInclusion: ALWAYS ``` -------------------------------- ### Start all engines with BeanProvider (Groovy) Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/index.html Groovy method to start all engines if any are present, using isPresent and each. ```groovy void startAll() { if (engineProvider.isPresent()) { // (1) engineProvider.each {it.start() } // (2) } } ``` -------------------------------- ### Start all engines with BeanProvider (Java) Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/index.html Method to start all engines if any are present, using isPresent and stream().forEach(). ```java void startAll() { if (engineProvider.isPresent()) { // (1) engineProvider.stream().forEach(Engine::start); // (2) } } ``` -------------------------------- ### ConfigurationBuilder Example (Kotlin) Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/index.html Kotlin version of the @ConfigurationBuilder example, using property syntax and @set:ConfigurationBuilder for the setter. The annotation uses prefixes as an array. ```kotlin import io.micronaut.context.annotation.ConfigurationBuilder import io.micronaut.context.annotation.ConfigurationProperties @ConfigurationProperties("my.engine") // (1) internal class EngineConfig { @ConfigurationBuilder(prefixes = ["with"]) // (2) val builder = EngineImpl.builder() @ConfigurationBuilder(prefixes = ["with"], configurationPrefix = "crank-shaft") // (3) val crankShaft = CrankShaft.builder() @set:ConfigurationBuilder(prefixes = ["with"], configurationPrefix = "spark-plug") // (4) var sparkPlug = SparkPlug.builder() } ``` -------------------------------- ### ConfigurationBuilder Example (Groovy) Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/index.html Groovy version of the @ConfigurationBuilder example, demonstrating the same configuration with Groovy syntax. The annotation is applied to fields and a setter method. ```groovy import io.micronaut.context.annotation.ConfigurationBuilder import io.micronaut.context.annotation.ConfigurationProperties @ConfigurationProperties('my.engine') // (1) class EngineConfig { @ConfigurationBuilder(prefixes = "with") // (2) EngineImpl.Builder builder = EngineImpl.builder() @ConfigurationBuilder(prefixes = "with", configurationPrefix = "crank-shaft") // (3) CrankShaft.Builder crankShaft = CrankShaft.builder() SparkPlug.Builder sparkPlug = SparkPlug.builder() @ConfigurationBuilder(prefixes = "with", configurationPrefix = "spark-plug") // (4) void setSparkPlug(SparkPlug.Builder sparkPlug) { this.sparkPlug = sparkPlug } } ``` -------------------------------- ### Configuring Versioning with Header and Parameter Strategies Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/index.html Full configuration example showing how to enable versioning, disable parameter-based versioning, specify parameter names, enable header-based versioning, and list header names. ```yaml micronaut: router: versioning: enabled: true (1) parameter: enabled: false (2) names: 'v,api-version' (3) header: enabled: true (4) names: (5) - 'X-API-VERSION' - 'Accept-Version' ``` -------------------------------- ### Running the Native Application Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/index.html Run the built native image by its name. The output shows startup completes in milliseconds and the server runs at http://localhost:8080. ```bash $ ./hello-world 15:15:15.153 [main] INFO io.micronaut.runtime.Micronaut - Startup completed in 14ms. Server Running: http://localhost:8080 ``` -------------------------------- ### @Read Method - Basic GET Endpoint Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/index.html Annotating a method with @Read causes it to respond to GET requests. The example shows a CurrentDateEndpoint that returns the current date as JSON. ```APIDOC ## [GET] /date ### Description Annotating a method with @Read causes it to respond to GET requests. This example returns the current date. ### Method GET ### Endpoint /date ### Parameters No parameters. ### Request Example ```bash $ curl -X GET localhost:55838/date ``` ### Response #### Success Response (200) - **currentDate** (Date) - The current date as a timestamp. #### Response Example ``` 1526085903689 ``` ``` -------------------------------- ### Define immutable configuration with @ConfigurationProperties interface (Kotlin) Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/index.html Kotlin version of the immutable configuration interface example. Uses Kotlin properties with @get:Bindable and @get:NotBlank annotations. ```kotlin import io.micronaut.context.annotation.ConfigurationProperties import io.micronaut.core.bind.annotation.Bindable import javax.validation.constraints.Min import javax.validation.constraints.NotBlank import javax.validation.constraints.NotNull @ConfigurationProperties("my.engine") // (1) interface EngineConfig { @get:Bindable(defaultValue = "Ford") // (2) @get:NotBlank // (3) val manufacturer: String @get:Min(1L) val cylinders: Int @get:NotNull val crankShaft: CrankShaft // (4) @ConfigurationProperties("crank-shaft") interface CrankShaft { // (5) val rodLength: Double? // (6) } } ``` -------------------------------- ### BintrayService HTTP client example (Groovy) Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/index.html Groovy version of the BintrayService example, using Groovy string interpolation for URLs and the same configuration injection. ```groovy class BintrayApi { public static final String URL = 'https://api.bintray.com' } @Singleton class BintrayService { final HttpClient client final String org BintrayService( @Client(BintrayApi.URL) HttpClient client, // (1) @Value('${bintray.organization}') String org ) { this.client = client this.org = org } Flux> fetchRepositories() { client.exchange(HttpRequest.GET("/repos/$org"), String) // (2) } Flux> fetchPackages(String repo) { client.exchange(HttpRequest.GET("/repos/${org}/${repo}/packages"), String) // (2) } } ``` -------------------------------- ### Factory bean from field (Kotlin) Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/index.html Kotlin version of the factory bean from field example. Uses @get:Bean and @get:Replaces annotations on a property, and JUnit 5 for testing. ```kotlin @MicronautTest class VehicleMockSpec { @get:Bean @get:Replaces(Engine::class) val mockEngine: Engine = object : Engine { // (1) override fun start(): String { return "Mock Started" } } @Inject lateinit var vehicle : Vehicle // (2) @Test fun testStartEngine() { val result = vehicle.start() Assertions.assertEquals("Mock Started", result) // (3) } } ``` -------------------------------- ### micronaut-cli.yml configuration example Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/ Example `micronaut-cli.yml` file that sets the default package, test framework, and source language. These settings are honored by all code-generation commands. ```yaml defaultPackage: example --- testFramework: spock sourceLanguage: java ``` -------------------------------- ### Install GraalVM 22.0.0.2 with SDKman Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/index.html Install and use GraalVM 22.0.0.2.r11-grl via SDKman. This is required for building native images without Docker. ```bash $ sdk install java 22.0.0.2.r11-grl $ sdk use java 22.0.0.2.r11-grl ``` -------------------------------- ### ResourceBundleMessageSource Example (Java) Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/index.html Retrieves messages using the messageSource bean. Uses MessageContext.of with a Locale to get localized messages. The example asserts that 'hello' returns 'Hola' for Spanish and 'Hello' for English. ```java assertEquals("Hola", messageSource.getMessage("hello", MessageContext.of(new Locale("es"))).get()); assertEquals("Hello", messageSource.getMessage("hello", MessageContext.of(Locale.ENGLISH)).get()); ``` -------------------------------- ### @Value Example (Java) Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/index.html Java example of injecting a property with a default value using @Value. The placeholder ${my.engine.cylinders:6} injects 6 if the property is missing. The injected value is used in the start() method. ```java import io.micronaut.context.annotation.Value; import jakarta.inject.Singleton; @Singleton public class EngineImpl implements Engine { @Value("${my.engine.cylinders:6}") // (1) protected int cylinders; @Override public int getCylinders() { return cylinders; } @Override public String start() {// (2) return "Starting V" + getCylinders() + " Engine"; } } ``` -------------------------------- ### Supply configuration (Java) Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/index.html Shows how to run an ApplicationContext with configuration values for my.engine.cylinders and my.engine.crank-shaft.rod-length, then retrieve a Vehicle bean and print its start message. ```java ApplicationContext applicationContext = ApplicationContext.run(CollectionUtils.mapOf( "my.engine.cylinders", "8", "my.engine.crank-shaft.rod-length", "7.0" )); Vehicle vehicle = applicationContext.getBean(Vehicle.class); System.out.println(vehicle.start()); ``` -------------------------------- ### Create application my-demo-app with default package Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/index.html Running 'mn create-app my-demo-app' results in the default package 'my.demo.app'. ```bash $ mn create-app my-demo-app ``` -------------------------------- ### Start All Engines with BeanProvider (Kotlin) Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/ Iterates over all available Engine beans using BeanProvider's forEach method to start each engine if any are present. ```kotlin fun startAll() { if (engineProvider.isPresent) { // (1) engineProvider.forEach { it.start() } // (2) } } ``` -------------------------------- ### EnvironmentEndpointFilter with maskNone and exclude patterns Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/ Use this filter to allow all environment values in plain text except those matching specified patterns. The example masks names starting with 'sekrt', exactly matching 'exact-match', or starting with 'private.'. ```java @Singleton public class AllPlainExceptSecretOrMatchEnvFilter implements EnvironmentEndpointFilter { // Mask anything starting with `sekrt` private static final Pattern SECRET_PREFIX_PATTERN = Pattern.compile("sekrt.*", Pattern.CASE_INSENSITIVE); // Mask anything exactly matching `exact-match` private static final String EXACT_MATCH = "exact-match"; // Mask anything that starts with `private.` private static final Predicate PREDICATE_MATCH = name -> name.startsWith("private."); @Override public void specifyFiltering(@NotNull EnvironmentFilterSpecification specification) { specification .maskNone() // All values will be in plain-text apart from the supplied patterns .exclude(SECRET_PREFIX_PATTERN) .exclude(EXACT_MATCH) .exclude(PREDICATE_MATCH); } } ``` -------------------------------- ### List available features with --list-features Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/ Use `create-app --list-features` to display available features. The output shows a table of features with descriptions, and features included by default are marked with a plus sign. ```bash mn> create-app --list-features Available Features (+) denotes the feature is included by default Name Description ------------------------------- --------------- Cache cache-caffeine Adds support for cache using Caffeine (https://github.com/ben-manes/caffeine) cache-ehcache Adds support for cache using EHCache (https://www.ehcache.org/) cache-hazelcast Adds support for cache using Hazelcast (https://hazelcast.org/) cache-infinispan Adds support for cache using Infinispan (https://infinispan.org/) ``` -------------------------------- ### Defining a main entry point with Micronaut.run Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/index.html Place this call in the main method to start the Micronaut HTTP server. The passed arguments are transformed into a CommandLinePropertySource and available for dependency injection via @Value. ```java public static void main(String[] args) { Micronaut.run(Application.class, args); } ``` -------------------------------- ### Using @Property to resolve sub-maps Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/index.html Example of using @Property to inject a flattened map containing only properties starting with 'hibernate' from the 'jpa.default.properties' configuration. ```java @Property(name = "jpa.default.properties") Map jpaProperties; ``` -------------------------------- ### Create-Client Command Example Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/index.html Generates a Client interface following a *Client convention. Does not create an associated test. ```bash $ mn create-client Book | Rendered template Client.java to destination src/main/java/example/BookClient.java ``` -------------------------------- ### Micronaut Groovy controller with @Controller Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/ Example Groovy controller generated by the CLI. Uses `@Controller("/hello")` and `@Get` to return `HttpStatus.OK`. ```groovy package hello.world import io.micronaut.http.annotation.Controller import io.micronaut.http.annotation.Get import io.micronaut.http.HttpStatus @Controller("/hello") class HelloController { @Get HttpStatus index() { return HttpStatus.OK } } ``` -------------------------------- ### Using retrieve to perform an HTTP GET (Kotlin) Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/index.html Shows how to use the retrieve method to execute an HTTP GET and receive the response body as a String. The example builds a URI with UriBuilder and expands a template variable. It calls toBlocking() for illustration, but production code should avoid blocking. ```kotlin val uri = UriBuilder.of("/hello/{name}") .expand(Collections.singletonMap("name", "John")) .toString() uri shouldBe "/hello/John" val result = client.toBlocking().retrieve(uri) result shouldBe "Hello John" ``` -------------------------------- ### Using retrieve to perform an HTTP GET (Groovy) Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/index.html Shows how to use the retrieve method to execute an HTTP GET and receive the response body as a String. The example builds a URI with UriBuilder and expands a template variable. It calls toBlocking() for illustration, but production code should avoid blocking. ```groovy when: String uri = UriBuilder.of("/hello/{name}") .expand(name: "John") then: "/hello/John" == uri when: String result = client.toBlocking().retrieve(uri) then: "Hello John" == result ``` -------------------------------- ### Using retrieve to perform an HTTP GET (Java) Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/index.html Shows how to use the retrieve method to execute an HTTP GET and receive the response body as a String. The example builds a URI with UriBuilder and expands a template variable. It calls toBlocking() for illustration, but production code should avoid blocking. ```java String uri = UriBuilder.of("/hello/{name}") .expand(Collections.singletonMap("name", "John")) .toString(); assertEquals("/hello/John", uri); String result = client.toBlocking().retrieve(uri); assertEquals("Hello John", result); ``` -------------------------------- ### Create a Micronaut application using curl and unzip Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/index.html Alternative to the CLI: download the project zip from Micronaut Launch using curl, unzip it, and change into the project directory. Add ?build=maven to the URL to generate a Maven project. ```bash curl https://launch.micronaut.io/hello-world.zip -o hello-world.zip unzip hello-world.zip cd hello-world ``` -------------------------------- ### Supply configuration (Kotlin) Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/index.html Kotlin version of supplying configuration values to ApplicationContext.run and printing the vehicle start message. ```kotlin val map = mapOf( "my.engine.cylinders" to "8", "my.engine.crank-shaft.rod-length" to "7.0" ) val applicationContext = ApplicationContext.run(map) val vehicle = applicationContext.getBean(Vehicle::class.java) println(vehicle.start()) ``` -------------------------------- ### Schedule with Initial Delay using @Scheduled(initialDelay) Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/index.html Use the initialDelay member to run a task once after the server starts. The example runs once, one minute after startup. ```java @Scheduled(initialDelay = "1m") void onceOneMinuteAfterStartup() { System.out.println("Executing onceOneMinuteAfterStartup()"); } ``` ```groovy @Scheduled(initialDelay = "1m") void onceOneMinuteAfterStartup() { println "Executing onceOneMinuteAfterStartup()" } ``` ```kotlin @Scheduled(initialDelay = "1m") internal fun onceOneMinuteAfterStartup() { println("Executing onceOneMinuteAfterStartup()") } ``` -------------------------------- ### Retrieving the AUTHORIZATION_INFO header (Kotlin) Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/index.html Kotlin example showing how to retrieve the AUTHORIZATION_INFO header from the response of a GET request to /shopping/cart. The header is present in the response and the cart is not null. ```kotlin var response = Flux.from(client.exchange(HttpRequest.GET("/shopping/cart"), Cart::class.java)) // (1) .blockFirst() var cart = response.body() assertNotNull(response.header(HttpHeaders.AUTHORIZATION_INFO)) // (2) assertNotNull(cart) cart.items.isEmpty() ``` -------------------------------- ### Retrieving the AUTHORIZATION_INFO header (Groovy) Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/index.html Groovy example showing how to retrieve the AUTHORIZATION_INFO header from the response of a GET request to /shopping/cart. The header is present in the response and the cart is not null. ```groovy when: "The shopping cart is retrieved" HttpResponse response = client.exchange(HttpRequest.GET('/shopping/cart'), Cart) // (1) .blockFirst() Cart cart = response.body() then: "The shopping cart is present as well as a session id header" response.header(HttpHeaders.AUTHORIZATION_INFO) != null // (2) cart != null cart.items.isEmpty() ``` -------------------------------- ### Start a Maven project Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/index.html Command to run a generated Micronaut Maven project. ```bash $ ./mvnw mn:run ``` -------------------------------- ### Bind configuration from map (Kotlin) Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/index.html Kotlin setup using @BeforeEach and @AfterEach to run and close the ApplicationContext with a map for 'myapp.updatedAt'. ```kotlin lateinit var ctx: ApplicationContext @BeforeEach fun setup() { ctx = ApplicationContext.run( mapOf( "myapp.updatedAt" to mapOf( // (1) "day" to 28, "month" to 10, "year" to 1982 ) ) ) } @AfterEach fun teardown() { ctx?.close() } ``` -------------------------------- ### Retrieving the AUTHORIZATION_INFO header (Java) Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/index.html Java example showing how to retrieve the AUTHORIZATION_INFO header from the response of a GET request to /shopping/cart. The header is present in the response and the cart is not null. ```java HttpResponse response = Flux.from(client.exchange(HttpRequest.GET("/shopping/cart"), Cart.class)) // (1) .blockFirst(); Cart cart = response.body(); assertNotNull(response.header(HttpHeaders.AUTHORIZATION_INFO)); // (2) assertNotNull(cart); assertTrue(cart.getItems().isEmpty()); ``` -------------------------------- ### Supply Configuration with Map (Java) Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/index.html Creates an ApplicationContext with a map containing 'my.engine.cylinders' and the 'test' environment, then retrieves a Vehicle bean and prints its start message. ```java Map map = new LinkedHashMap<>(1); map.put("my.engine.cylinders", "8"); ApplicationContext applicationContext = ApplicationContext.run(map, "test"); Vehicle vehicle = applicationContext.getBean(Vehicle.class); System.out.println(vehicle.start()); ``` -------------------------------- ### Micronaut Groovy client with @Client Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/ Example Groovy client interface generated by the CLI. Uses `@Client("hello")` and `@Get` to define an HTTP client. ```groovy package hello.world import io.micronaut.http.client.annotation.Client import io.micronaut.http.annotation.Get import io.micronaut.http.HttpStatus @Client("hello") interface HelloClient { @Get HttpStatus index() } ``` -------------------------------- ### Set rebelAgent property in gradle.properties Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/index.html Add the path to the JRebel agent as the rebelAgent property in gradle.properties. The example assumes an installation path of ~/bin/jrebel/ and uses the macOS 64-bit agent. ```properties #Assuming installation path of ~/bin/jrebel/ rebelAgent= -agentpath:~/bin/jrebel/lib/libjrebel64.dylib ``` -------------------------------- ### Create-Controller Command Example Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/index.html Generates a Controller class following a *Controller convention. Creates an associated test that runs the application and instantiates an HTTP client. ```bash $ mn create-controller Book | Rendered template Controller.java to destination src/main/java/example/BookController.java | Rendered template ControllerTest.java to destination src/test/java/example/BookControllerTest.java ``` -------------------------------- ### Specifying environments with micronaut.environments Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/index.html Command-line example that activates environments 'foo' and 'bar' using the micronaut.environments system property. ```bash $ java -Dmicronaut.environments=foo,bar -jar myapp.jar ``` -------------------------------- ### Supply Configuration with Map (Groovy) Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/index.html Creates an ApplicationContext with a map containing 'my.engine.cylinders' and the 'test' environment, then retrieves a Vehicle bean and prints its start message. ```groovy ApplicationContext applicationContext = ApplicationContext.run( ['my.engine.cylinders': '8'], "test" ) def vehicle = applicationContext.getBean(Vehicle) println(vehicle.start()) ``` -------------------------------- ### URI Variables Example (Kotlin) Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/index.html Kotlin controller mapping /issues/{number} with @PathVariable number: Int. The @Controller base URI is /issues and the @Get annotation embeds the {number} variable. ```kotlin import io.micronaut.http.annotation.Controller import io.micronaut.http.annotation.Get import io.micronaut.http.annotation.PathVariable @Controller("/issues") // (1) class IssuesController { @Get("/{number}") // (2) fun issue(@PathVariable number: Int): String { // (3) return "Issue # $number!" // (4) } } ``` -------------------------------- ### Info Endpoint Configuration Example Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/ YAML configuration for the info endpoint, enabling or disabling it and setting sensitivity. ```yaml endpoints: info: enabled: Boolean sensitive: Boolean ``` -------------------------------- ### URI Variables Example (Groovy) Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/index.html Groovy controller mapping /issues/{number} with @PathVariable Integer number. The @Controller base URI is /issues and the @Get annotation embeds the {number} variable. ```groovy import io.micronaut.http.annotation.Controller import io.micronaut.http.annotation.Get import io.micronaut.http.annotation.PathVariable @Controller("/issues") // (1) class IssuesController { @Get("/{number}") // (2) String issue(@PathVariable Integer number) { // (3) "Issue # " + number + "!" // (4) } } ``` -------------------------------- ### Supply Configuration with Map (Kotlin) Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/index.html Creates an ApplicationContext with a map containing 'my.engine.cylinders' and the 'test' environment, then retrieves a Vehicle bean and prints its start message. ```kotlin val map = mapOf( "my.engine.cylinders" to "8") val applicationContext = ApplicationContext.run(map, "test") val vehicle = applicationContext.getBean(Vehicle::class.java) println(vehicle.start()) ``` -------------------------------- ### URI Variables Example (Java) Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/index.html Java controller mapping /issues/{number} with @PathVariable Integer number. The @Controller base URI is /issues and the @Get annotation embeds the {number} variable. ```java import io.micronaut.http.annotation.Controller; import io.micronaut.http.annotation.Get; import io.micronaut.http.annotation.PathVariable; @Controller("/issues") // (1) public class IssuesController { @Get("/{number}") // (2) public String issue(@PathVariable Integer number) { // (3) return "Issue # " + number + "!"; // (4) } } ``` -------------------------------- ### Test invoking HeadlineClient (Kotlin) Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/index.html Kotlin test that retrieves the client bean, uses next() to get the first element, and blocks. Asserts the headline text starts with 'Latest Headline'. ```kotlin "test client annotation streaming" { val headlineClient = embeddedServer .applicationContext .getBean(HeadlineClient::class.java) // (1) val firstHeadline = headlineClient.streamHeadlines().next() // (2) val headline = firstHeadline.block() // (3) headline shouldNotBe null headline.text shouldStartWith "Latest Headline" } ``` -------------------------------- ### Supply configuration (Groovy) Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/index.html Groovy version of supplying configuration values to ApplicationContext.run and printing the vehicle start message. ```groovy ApplicationContext applicationContext = ApplicationContext.run( "my.engine.cylinders": "8", "my.engine.crank-shaft.rod-length": "7.0" ) Vehicle vehicle = applicationContext.getBean(Vehicle) System.out.println(vehicle.start()) ``` -------------------------------- ### Test the Hello World endpoint with curl Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/index.html Send a GET request to /hello and receive the text 'Hello World' as the response. ```bash $ curl http://localhost:8080/hello Hello World ``` -------------------------------- ### Create a basic Micronaut application with create-app Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/index.html Creates a standard server application that communicates over HTTP. Supports options for language, test framework, build tool, features, and in-place generation. ```bash mn create-app my-project --features mongo-reactive,security-jwt --build maven ``` -------------------------------- ### MovieTicketController with @RequestBean (Kotlin) Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/index.html Kotlin controller example showing how to bind multiple Bindable values to a POJO using @RequestBean. The @Get annotation includes optional query parameters minPrice and maxPrice. ```kotlin @Controller("/api") open class MovieTicketController { // You can also omit query parameters like: // @Get("/movie/ticket/{movieId} @Get("/movie/ticket/{movieId}{?minPrice,maxPrice}") open fun list(@Valid @RequestBean bean: MovieTicketBean): HttpStatus { return HttpStatus.OK } } ``` -------------------------------- ### Build native image with Docker and Maven Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/index.html Run the Maven command with -Dpackaging=docker-native to build a native image using Docker. ```bash $ ./mvnw package -Dpackaging=docker-native ``` -------------------------------- ### MovieTicketController with @RequestBean (Groovy) Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/index.html Groovy controller example showing how to bind multiple Bindable values to a POJO using @RequestBean. The @Get annotation includes optional query parameters minPrice and maxPrice. ```groovy @Controller("/api") class MovieTicketController { // You can also omit query parameters like: // @Get("/movie/ticket/{movieId} @Get("/movie/ticket/{movieId}{?minPrice,maxPrice}") HttpStatus list(@Valid @RequestBean MovieTicketBean bean) { HttpStatus.OK } } ``` -------------------------------- ### MovieTicketController with @RequestBean (Java) Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/index.html Java controller example showing how to bind multiple Bindable values to a POJO using @RequestBean. The @Get annotation includes optional query parameters minPrice and maxPrice. ```java @Controller("/api") public class MovieTicketController { // You can also omit query parameters like: // @Get("/movie/ticket/{movieId} @Get("/movie/ticket/{movieId}{?minPrice,maxPrice}") public HttpStatus list(@Valid @RequestBean MovieTicketBean bean) { return HttpStatus.OK; } } ``` -------------------------------- ### V8Engine with @PostConstruct in Java Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/ Java example of a singleton bean that uses @PostConstruct to initialize a field after construction and injection. The initialize() method sets initialized to true, and start() throws IllegalStateException if not initialized. ```java import jakarta.annotation.PostConstruct; // (1) import jakarta.inject.Singleton; @Singleton public class V8Engine implements Engine { private int cylinders = 8; private boolean initialized = false; // (2) @Override public String start() { if (!initialized) { throw new IllegalStateException("Engine not initialized!"); } return "Starting V8"; } @Override public int getCylinders() { return cylinders; } public boolean isInitialized() { return initialized; } @PostConstruct // (3) public void initialize() { initialized = true; } } ``` -------------------------------- ### Show create-app help with -h flag Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/ Use `create-app -h` in interactive mode to display usage information for the create-app command, including options for build tool, language, test framework, and features. ```bash mn> create-app -h Usage: mn create-app [-hivVx] [--list-features] [-b=BUILD-TOOL] [--jdk=] [-l=LANG] [-t=TEST] [-f=FEATURE[,FEATURE...]]... [NAME] Creates an application [NAME] The name of the application to create. -b, --build=BUILD-TOOL Which build tool to configure. Possible values: gradle, gradle_kotlin, maven. -f, --features=FEATURE[,FEATURE...] -h, --help Show this help message and exit. -i, --inplace Create a service using the current directory --jdk, --java-version= The JDK version the project should target -l, --lang=LANG Which language to use. Possible values: java, groovy, kotlin. --list-features Output the available features and their descriptions -t, --test=TEST Which test framework to use. Possible values: junit, spock, kotest. ``` -------------------------------- ### @EachProperty List Example (Kotlin) Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/index.html Kotlin version of the RateLimitsConfiguration class using @EachProperty with list=true and implementing Ordered. ```kotlin import io.micronaut.context.annotation.EachProperty import io.micronaut.context.annotation.Parameter import io.micronaut.core.order.Ordered import java.time.Duration @EachProperty(value = "ratelimits", list = true) // (1) class RateLimitsConfiguration constructor(@param:Parameter private val index: Int) // (3) : Ordered { // (2) var period: Duration? = null var limit: Int? = null override fun getOrder(): Int { return index } } ``` -------------------------------- ### Basic @Read method in Kotlin Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/index.html Kotlin example of a management endpoint with a @Read method that responds to GET requests. The endpoint is configured with id 'date', prefix 'custom', defaultEnabled true, and defaultSensitive false. ```kotlin import io.micronaut.management.endpoint.annotation.Endpoint import io.micronaut.management.endpoint.annotation.Read @Endpoint(id = "date", prefix = "custom", defaultEnabled = true, defaultSensitive = false) class CurrentDateEndpoint { private var currentDate: Date? = null @Read fun currentDate(): Date? { return currentDate } } ``` -------------------------------- ### Basic @Read method in Groovy Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/index.html Groovy example of a management endpoint with a @Read method that responds to GET requests. The endpoint is configured with id 'date', prefix 'custom', defaultEnabled true, and defaultSensitive false. ```groovy import io.micronaut.management.endpoint.annotation.Endpoint import io.micronaut.management.endpoint.annotation.Read @Endpoint(id = "date", prefix = "custom", defaultEnabled = true, defaultSensitive = false) class CurrentDateEndpoint { private Date currentDate @Read Date currentDate() { currentDate } } ``` -------------------------------- ### Basic @Read method in Java Source: https://micronaut-projects.github.io/micronaut-core/latest/guide/index.html Java example of a management endpoint with a @Read method that responds to GET requests. The endpoint is configured with id 'date', prefix 'custom', defaultEnabled true, and defaultSensitive false. ```java import io.micronaut.management.endpoint.annotation.Endpoint; import io.micronaut.management.endpoint.annotation.Read; @Endpoint(id = "date", prefix = "custom", defaultEnabled = true, defaultSensitive = false) public class CurrentDateEndpoint { private Date currentDate; @Read public Date currentDate() { return currentDate; } } ```