LShubinaDev
LShubinaDev

Reputation: 13

Set micronaut environment variable in runtime

I want to set micronaut application name programatically, something like

@Singleton
public class AppNameInitializer {
    @Inject
    public void initAppName(Environment env) {
        if (CollectionUtils.isNotEmpty(env.getActiveNames()) ){
            // i want to set property 'micronaut.application.name' to app-with-profiles
        } else {
            // i want to set property 'micronaut.application.name' to app-without-profiles
        }
    }
}

How can I do that? I tried that using

@Singleton
public class AppNameInitializer {
    @Inject
    public void initAppName(Environment env) {
        String propertyLowercase = "micronaut.application.name";
        // for some reason
        String propertyUppercase = "MICRONAUT_APPLICATION_NAME";
        String appNameWithProfiles = "app-with-profiles";
        String appNameWithoutProfiles = "app-without-profiles";
        if (CollectionUtils.isNotEmpty(env.getActiveNames()) ){
            System.setProperty(propertyLowercase, appNameWithProfiles);
            System.setProperty(propertyUppercase, appNameWithProfiles);
        } else {
            System.setProperty(propertyLowercase, appNameWithoutProfiles);
            System.setProperty(propertyUppercase, appNameWithoutProfiles);
        }
    }
}

That didn't work

Upvotes: 0

Views: 825

Answers (1)

saw303
saw303

Reputation: 9082

Since the application is defined in the application.yml there is no need to add additional code. But you could introduce an environment variable like in this example:

micronaut:
  application:
    name: "${MY_APP_NAME:default-name}"

In the example above you can use the environment variable MY_APP_NAME to set the application name. If the env variable is not set, the application will use the default name default-name.

Upvotes: 2

Related Questions