1. Overview

In Micronaut, similar to other Java frameworks, the Environment interface is an abstraction related to profiles. Profiles are a concept that we can think of as containers, that hold properties and beans specific to them.

Usually, the profiles are related to the execution environment, such as local-profile, docker-profile, k8s-profile, etc. We can use Micronaut environments to create different sets of properties, in .properties or .yaml files, depending on whether we execute our application locally, on the cloud, etc.

In this tutorial, we’ll go through the Environment abstraction in Micronaut and we’ll see different ways to set it properly. Last, we’ll learn how we can use the environment-specific properties and beans, and also how we can use environments to apply different implementations.

2. Micronaut Environments vs. Spring Profiles

If we’re familiar with Spring profiles, then understanding Micronaut environments is easy. There are many similarities, but also a few key differences.

Using Micronaut environments, we can set properties in similar ways as in Spring. This means we can have:

  • property files using the @ConfigurationProperties annotation
  • inject specific properties to a class using the @Value annotation
  • inject specific properties to a class by injecting the whole Environment instance and then use the getProperty() method

One confusing difference between Spring and Micronaut is that although both allow multiple active environments/profiles, in Micronaut it’s common to see many active environments, while in Spring profiles we rarely see more than one active profile. This leads to some confusion about properties or beans that are specified in many active environments. To overcome this, we can set environment priorities. More on that later.

Another difference worth noting is that Micronaut gives an option to disable environments completely. This isn’t relevant in Spring profiles, since when don’t set the active profile, the default is usually being used. In contrast, Micronaut might have different active environments set from different frameworks or tools used. For example:

  • JUnit adds in active environments the ‘test’ environment
  • Cucumber adds the ‘cucumber’ environment
  • OCI might add ‘cloud’ and/or ‘k8s’, etc.

In order to disable environments we can use java -Dmicronaut.env.deduction=false -jar myapp.jar.

3. Setting Micronaut Environments

There are different ways to set Micronaut environments. The most common ones are:

  • Using the micronaut.environments argument: java -Dmicronaut.environments=cloud,production -jar myapp.jar.
  • Using the defaultEnvironment() method in main(): Micronaut.build(args).defaultEnvironments(‘local’).mainClass(MicronautServiceApi.class).start();.
  • Setting the value in MICRONAUT_ENV, as an environmental variable.
  • As we noted earlier, environments sometimes are deducted, meaning set from frameworks in the background, like JUnit and Cucumber.

There are no best practices in the way we decide to set the environment. We can choose the one that best fits our needs.

4. Micronaut Environments Priority and Resolution

Since multiple active Micronaut environments are allowed, then there are cases in which a property or a bean might have been explicitly defined in more than one or none of them. This leads to conflicts and sometimes in runtime exceptions. The way properties and beans’ priority and resolution are handled is different.

4.1. Properties

When a property exists in multiple active property sources, the environment order determines which value it gets. The hierarchy, from lowest to highest order, is:

  • deduced environments from other tools/frameworks
  • environments set in the micronaut.environments argument
  • environments set in MICRONAUT_ENV environment variable
  • environments loaded in the Micronaut builder

Let’s assume we have a property service.test.property and we want to have different values for it, in different environments. We set the different values in application-dev.yml and application-test.yml files:

@Test
public void whenEnvironmentIsNotSet_thenTestPropertyGetsValueFromDeductedEnvironment() {
    ApplicationContext applicationContext = Micronaut.run(ServerApplication.class);
    applicationContext.start();

    assertThat(applicationContext.getEnvironment()
      .getActiveNames()).containsExactly("test");
    assertThat(applicationContext.getProperty("service.test.property", String.class)).isNotEmpty();
    assertThat(applicationContext.getProperty("service.test.property", String.class)
      .get()).isEqualTo("something-in-test");
}

@Test
public void whenEnvironmentIsSetToBothProductionAndDev_thenTestPropertyGetsValueBasedOnPriority() {
    ApplicationContext applicationContext = ApplicationContext.builder("dev", "production").build();
    applicationContext.start();

    assertThat(applicationContext.getEnvironment()
      .getActiveNames()).containsExactly("test", "dev", "production");
    assertThat(applicationContext.getProperty("service.test.property", String.class)).isNotEmpty();
    assertThat(applicationContext.getProperty("service.test.property", String.class)
      .get()).isEqualTo("something-in-dev");
}

In the first test, we didn’t set any active environment, but there is the deducted test from JUnit. The property gets its value from application-test.yml in this case. But in the second example, we set in ApplicationContext, which has a higher order, the dev environment too. In this scenario, the property gets its value from application-dev.yml.

But if we try to inject a property that isn’t present in any of the active environments, we’ll get a runtime error, DependencyInjectionException, because of the missing property:

@Test
public void whenEnvironmentIsSetToBothProductionAndDev_thenMissingPropertyIsEmpty() {
    ApplicationContext applicationContext = ApplicationContext.builder("dev", "production")
      .build();
    applicationContext.start();

    assertThat(applicationContext.getEnvironment()
      .getActiveNames()).containsExactly("test", "dev", "production");
    assertThat(applicationContext.getProperty("service.dummy.property", String.class)).isEmpty();
}

In this example, we try to retrieve a missing property, system.dummy.property, directly from the ApplicationContext. This returns an empty Optional. If the property was injected in some bean, it would have caused a runtime exception.

4.2. Beans

With environment-specific beans, things are a bit more complex. Let’s assume we have an interface EventSourcingService that has one method sendEvent() (it should have been void, but we return the String for demo purposes):

public interface EventSourcingService {
    String sendEvent(String event);
}

There are only two implementations of this interface, one for environment dev and one for production:

@Singleton
@Requires(env = Environment.DEVELOPMENT)
public class VoidEventSourcingService implements EventSourcingService {
    @Override
    public String sendEvent(String event) {
        return "void service. [" + event + "] was not sent";
    }
}
@Singleton
@Requires(env = "production")
public class KafkaEventSourcingService implements EventSourcingService {
    @Override
    public String sendEvent(String event) {
        return "using kafka to send message: [" + event + "]";
    }
}

The @Requires annotation informs the framework that this implementation is only valid when one or more of the specified environment or environments are active. Or else, this bean is never created.

We can assume that the VoidEventSourcingService does nothing and only returns a String because maybe we don’t want to send events on dev environments. And KafkaEventSourcingService actually sends an event on a Kafka and then returns a String.

Now, what would happen if we forget to set in the active environments one or the other? In such a scenario, we’d be getting back a NoSuchBeanException exception:

public class InvalidEnvironmentEventSourcingUnitTest {
    @Test
    public void whenEnvironmentIsNotSet_thenEventSourcingServiceBeanIsNotCreated() {
        ApplicationContext applicationContext = Micronaut.run(ServerApplication.class);
        applicationContext.start();

        assertThat(applicationContext.getEnvironment().getActiveNames()).containsExactly("test");
        assertThatThrownBy(() -> applicationContext.getBean(EventSourcingService.class))
          .isInstanceOf(NoSuchBeanException.class)
          .hasMessageContaining("None of the required environments [production] are active: [test]");
    }
}

In this test, we don’t set any active environments. First, we assert that the only active environment is test, which is deduced from using the JUnit framework. Then we assert that if we try to get the bean of the implementation of EventSourcingService, we actually get an exception back, with an error indicating that none of the required environments are active.

On the contrary, if we set both environments, we get an error again, because both implementations of the interface cannot be present at the same time:

public class MultipleEnvironmentsEventSourcingUnitTest {
    @Test
    public void whenEnvironmentIsSetToBothProductionAndDev_thenEventSourcingServiceBeanHasConflict() {
        ApplicationContext applicationContext = ApplicationContext.builder("dev", "production").build();
        applicationContext.start();

        assertThat(applicationContext.getEnvironment()
          .getActiveNames()).containsExactly("test", "dev", "production");
        assertThatThrownBy(() -> applicationContext.getBean(EventSourcingService.class))
          .isInstanceOf(NonUniqueBeanException.class)
          .hasMessageContaining("Multiple possible bean candidates found: [VoidEventSourcingService, KafkaEventSourcingService]");
    }
}

This is not a bug or bad coding. This can be a real-life scenario, in which we might want to have failures when we forget to set the proper environment. But if we want to make sure we never get runtime errors in such cases, we can set a default implementation, by not adding the @Requires annotation. For the environments that we want to override the default, we should add the @Requires and the @Replaces annotations:

public interface LoggingService {
    // methods omitted
}

@Singleton
@Requires(env = { "production", "canary-production" })
@Replaces(LoggingService.class)
public class FileLoggingServiceImpl implements LoggingService {
    // implementation of the methods omitted
}

@Singleton
public class ConsoleLoggingServiceImpl implements LoggingService {
    // implementation of methods omitted
}

The LoggingService interface defines some methods. The default implementation is the ConsoleLoggingServiceImpl, which is applied to all environments. The FileLoggingServiceImpl class overrides the default implementation in production and canary-production environments.

5. Using the Micronaut Environments in Practice

Other than the environment-specific properties and beans, we can use the environments in some more cases. By injecting the Environment variable and using the getActiveNames() method, we can check in our code what the active environments are and alter some implementation details:

if (environment.getActiveNames().contains("production")
  || environment.getActiveNames().contains("canary-production")) {
    sendAuditEvent();
}

This snippet of code checks if the environment is production or canary-production and invokes the sendAuditEvent() method only in those two. This is of course a bad practice. Instead, we should use the strategy design pattern or specific beans, as demonstrated earlier.

But we still have the option. Some scenario that would be more common is to use this code in tests since our test code is sometimes simpler rather than cleaner:

if (environment.getActiveNames().contains("cloud")) {
    assertEquals(400, response.getStatusCode());
} else {
    assertEquals(500, response.getStatusCode());
}

This is a snippet of a test that might receive a 500 status response on the local environment because the service isn’t handling some error requests. On the other hand, a 400 status response is given on deployed environments, because the API Gateway responds before the request makes it to the service.

6. Conclusion

In this article, we learned about the Micronaut environments. We went through the main concepts, and similarities to Spring profiles and listed the different ways we can set the active environments. Then, we saw how to resolve environment-specific beans and properties in cases of multiple environments set or none set. Last, we discussed how to use environments directly in our code, which is usually not a good practice.

As always, all the source code is available over on GitHub.