Friday, 12 May 2023

Micronaut: MapFormat: Bind the properties to a map

MapFormat annotation bind the properties to a map. You can apply either of following transformations to the MapFormat annotation.

 

a.   NESTED: A nested map has the any keys such as {@code foo.bar} transformed into a structure that is a map of maps such as JSON.

b.   FLAT: A flat map has the keys flattened such that {@code foo.bar} is a single map.

       

For example, following snippet define spring datasource configuration.

spring:   
  datasource:
    communicationtimeout: 6000
    jpa:
      hibernate:
        ddl-auto: none
    hikari:
      connection-timeout: 3000
      idle-timeout: 40000
      max-lifetime: 10000
      maximum-pool-size: 5

Below snippet map the datasource configuration to a map.

@Property(name = "spring.datasource")
@MapFormat(transformation = MapTransformation.FLAT)
protected Map<String, String> datasourceFlatMap;

Find the below working application.

 

Step 1: Create new maven project ‘micronaut-mapformat-demo’.

 

Step 2: Update pom.xml with maven dependencies.

 

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.sample.app</groupId>
  <artifactId>micronaut-mapformat-demo</artifactId>
  <version>1</version>

  <parent>
    <groupId>io.micronaut</groupId>
    <artifactId>micronaut-parent</artifactId>
    <version>3.7.3</version>
  </parent>


  <properties>
    <maven-compiler-plugin.version>3.8.1</maven-compiler-plugin.version>

    <maven.compiler.target>15</maven.compiler.target>
    <maven.compiler.source>15</maven.compiler.source>
  </properties>

  <dependencies>

    <dependency>
      <groupId>io.micronaut</groupId>
      <artifactId>micronaut-inject-java</artifactId>
    </dependency>

    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-simple</artifactId>
    </dependency>

  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>${maven-compiler-plugin.version}</version>
        <configuration>
          <annotationProcessorPaths>
            <path>
              <groupId>io.micronaut</groupId>
              <artifactId>micronaut-inject-java</artifactId>
            </path>
          </annotationProcessorPaths>
        </configuration>
      </plugin>

      <plugin>
        <artifactId>maven-assembly-plugin</artifactId>
        <configuration>
          <archive>
            <manifest>
              <mainClass>com.sample.app.App</mainClass>
            </manifest>
          </archive>
          <descriptorRefs>
            <descriptorRef>jar-with-dependencies</descriptorRef>
          </descriptorRefs>
        </configuration>

        <executions>
          <execution>
            <id>make-assembly</id>
            <phase>package</phase>
            <goals>
              <goal>single</goal>
            </goals>
          </execution>
        </executions>
      </plugin>


    </plugins>
  </build>
</project>

Step 3: Create application.yml file under src/main/resources folder.

 

application.yml

spring:   
  datasource:
    communicationtimeout: 6000
    jpa:
      hibernate:
        ddl-auto: none
    hikari:
      connection-timeout: 3000
      idle-timeout: 40000
      max-lifetime: 10000
      maximum-pool-size: 5

Step 4: Define AppConfig class.

 

AppConfig.java

package com.sample.app.configuration;

import java.util.Map;

import io.micronaut.context.annotation.Property;
import io.micronaut.core.convert.format.MapFormat;
import io.micronaut.core.convert.format.MapFormat.MapTransformation;
import jakarta.inject.Singleton;

@Singleton
public class AppConfig {

  @Property(name = "spring.datasource")
  @MapFormat(transformation = MapTransformation.FLAT)
  protected Map<String, String> datasourceFlatMap;

  @Property(name = "spring.datasource")
  @MapFormat(transformation = MapTransformation.NESTED)
  protected Map<String, String> datasourceNestedMap;

  public Map<String, String> getDatasourceFlatMap() {
    return datasourceFlatMap;
  }

  public void setDatasourceFlatMap(Map<String, String> datasourceFlatMap) {
    this.datasourceFlatMap = datasourceFlatMap;
  }

  public Map<String, String> getDatasourceNestedMap() {
    return datasourceNestedMap;
  }

  public void setDatasourceNestedMap(Map<String, String> datasourceNestedMap) {
    this.datasourceNestedMap = datasourceNestedMap;
  }

}

Step 5: Define main application class.

 

App.java

package com.sample.app;

import java.util.Map;

import com.sample.app.configuration.AppConfig;

import io.micronaut.context.ApplicationContext;

public class App {

  public static void main(String[] args) {

    try (ApplicationContext applicationContext = ApplicationContext.run()) {

      AppConfig appConfig = applicationContext.getBean(AppConfig.class);

      System.out.println("\nFlat map informaiton");
      Map<String, String> datasourceProperties = appConfig.getDatasourceFlatMap();
      for (String key : datasourceProperties.keySet()) {
        System.out.println(key + " -> " + datasourceProperties.get(key));
      }

      System.out.println("\nNested map informaiton");
      datasourceProperties = appConfig.getDatasourceNestedMap();
      for (String key : datasourceProperties.keySet()) {
        System.out.println(key + " -> " + datasourceProperties.get(key));
      }
    }

  }
}

Total project structure looks like below.





Build the project using mvn package command.

Navigate to the folder where pom.xml is located and execute the command ‘mvn package’.

 

Upon command successful execution, you can see the jar file ‘micronaut-mapformat-demo-1-jar-with-dependencies.jar’ in project target folder.

 

$ ls ./target/
archive-tmp
classes
generated-sources
generated-test-sources
maven-archiver
maven-status
micronaut-mapformat-demo-1-jar-with-dependencies.jar
micronaut-mapformat-demo-1.jar
test-classes

Execute below command to run the application.

$ java -jar ./target/micronaut-mapformat-demo-1-jar-with-dependencies.jar

Flat map informaiton
communicationtimeout -> 6000
jpa.hibernate.ddl-auto -> none
hikari.connection-timeout -> 3000
hikari.idle-timeout -> 40000
hikari.max-lifetime -> 10000
hikari.maximum-pool-size -> 5

Nested map informaiton
communicationtimeout -> 6000
jpa -> {hibernate={ddl-auto=none}}
hikari -> {connection-timeout=3000, idle-timeout=40000, max-lifetime=10000, maximum-pool-size=5}

You can download this application from this link.


 

Previous                                                    Next                                                    Home

No comments:

Post a Comment