Micronaut Custom Configuration and Property Injection

In modern cloud-native applications, externalizing configuration is key. Micronaut provides a powerful and easy-to-use mechanism for injecting custom properties and managing configuration.

In this guide, you will learn how to:

  • Create custom configuration classes
  • Inject properties into beans and services
  • Use application configuration files effectively

We’ll use Maven, Java, and the package com.kscodes.micronaut.advanced for demonstration.

Micronaut Custom Configuration and Property Injection

๐Ÿ“ฆ Maven Setup

Ensure you have the following dependencies in your pom.xml:

๐Ÿ› ๏ธ Step 1: Create Custom Configuration Class

Micronaut uses the @ConfigurationProperties annotation to bind external config properties to a POJO.

๐Ÿ”ธ com.kscodes.micronaut.advanced.config.AppSettings.java

๐Ÿ“ Step 2: Define Properties in application.yml

Micronaut will automatically bind these values to the AppSettings bean.

๐Ÿงฉ Step 3: Inject Configuration in a Service

You can inject the configuration bean using @Inject.

๐Ÿ”ธ com.kscodes.micronaut.advanced.service.AppService.java

๐Ÿงช Step 4: Run and Test

Create a main class to run and validate the injection.

๐Ÿ”ธ com.kscodes.micronaut.advanced.Application.java

Note: For testing, consider using @MicronautTest and @Property annotations to override values.

๐ŸŒ Supporting Multiple Environments

You can create environment-specific files like application-dev.yml, application-prod.yml:

Activate an environment using:

๐Ÿ” Bonus: Injecting Values Without a POJO

Micronaut also allows property injection using @Value:

This is useful for simple values, but for structured configuration, prefer @ConfigurationProperties.

โœ… Conclusion

Custom configuration and property injection in Micronaut make your applications clean, modular, and flexible for any environment.

Youโ€™ve learned:

  • How to bind properties with @ConfigurationProperties
  • How to inject configuration into services
  • How to manage profiles and environments

This approach aligns well with 12-factor app methodology and prepares your app for scalable deployment.