Partner – Orkes – NPI EA (cat=Spring)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag=Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Partner – LambdaTest – NPI EA (cat=Testing)
announcement - icon

Browser testing is essential if you have a website or web applications that users interact with. Manual testing can be very helpful to an extent, but given the multiple browsers available, not to mention versions and operating system, testing everything manually becomes time-consuming and repetitive.

To help automate this process, Selenium is a popular choice for developers, as an open-source tool with a large and active community. What's more, we can further scale our automation testing by running on theLambdaTest cloud-based testing platform.

Read more through our step-by-step tutorial on how to set up Selenium tests with Java and run them on LambdaTest:

>> Automated Browser Testing With Selenium

Partner – Orkes – NPI EA (cat=Java)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

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.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

Partner – Orkes – NPI EA (cat = Spring)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag = Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)