Monday, 1 May 2023

Micronaut: Inject a property value using @property annotation

@Property annotation is used to inject a value associated with given property name.

 

Example

@Property(name = "spring.datasource.communicationtimeout")
protected Integer communicationTimeout;

 

Above statement resolve the value associated with the property "spring.datasource.communicationtimeout" and inject it into the field ‘communicationTimeout’. As a recommendation from Micronaut, fields subject to injection should not be private because expensive reflection must be used.

 

Can I apply @Property annotation on setter method arguments?

Yes, you can.

 

@Inject
public void setVersion(@Property(name = "appVersion") String version) {
	this.version = version;
}

Resolve submaps using Property annotation

Example application.yml configuration

appName: chat server
appVersion: 1.23.45

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

To resolve a flattened map containing only the properties starting with hibernate, use @Property, for example: 

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

‘datasourceFlatMap’ contain below information.

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

If you do not specify any transformation explicitly, then it is NESTED by default.

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

‘datasourceNestedMap’ contain below information.

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

Find the below working application.

 

Step 1: Create new maven project ‘micronaut-property-annotation-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-property-annotation-demo</artifactId>
  <version>1</version>

  <properties>
    <maven-compiler-plugin.version>3.8.1</maven-compiler-plugin.version>
    <micronaut.version>3.7.3</micronaut.version>
    <slf4j.version>2.0.3</slf4j.version>
    <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>
      <version>${micronaut.version}</version>
    </dependency>

    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>${slf4j.version}</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-simple</artifactId>
      <version>${slf4j.version}</version>
    </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>
              <version>${micronaut.version}</version>
            </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

appName: chat server
appVersion: 1.23.45

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.configs;

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.Inject;
import jakarta.inject.Singleton;

@Singleton
public class AppConfig {

  @Property(name = "app-name")
  protected String name;

  protected String version;

  @Property(name = "spring.datasource.communicationtimeout")
  protected Integer communicationTimeout;

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

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

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public String getVersion() {
    return version;
  }

  @Inject
  public void setVersion(@Property(name = "appVersion") String version) {
    this.version = version;
  }

  public Integer getCommunicationTimeout() {
    return communicationTimeout;
  }

  public void setCommunicationTimeout(Integer communicationTimeout) {
    this.communicationTimeout = communicationTimeout;
  }

  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.configs.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);

      String appName = appConfig.getName();
      String version = appConfig.getVersion();
      Integer datasourceTimeout = appConfig.getCommunicationTimeout();

      System.out.println("appName : " + appName);
      System.out.println("version : " + version);
      System.out.println("datasourceTimeout : " + datasourceTimeout + "\n");

      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-property-annotation-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-property-annotation-demo-1-jar-with-dependencies.jar
micronaut-property-annotation-demo-1.jar
test-classes

Execute below command to run the application.

java -jar ./target/micronaut-property-annotation-demo-1-jar-with-dependencies.jar

$java -jar ./target/micronaut-property-annotation-demo-1-jar-with-dependencies.jar
appName : chat server
version : 1.23.45
datasourceTimeout : 6000


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