Search code examples
groovymicronaut

Inject RxHttpClient in Micronaut with url coming from an environment variable


When I am injecting a RxHttpClient in micronaut, I have an url with a token that I want to get from an environment variable to avoid hardcoding a secret.

In my service, I have injected the client like this:

@Client('${System.getenv(\'BOT_URL\')}')
@Inject
RxHttpClient httpClient

Being BOT_URL my url that's stored in an environment variable. The project build but it fails while trying to use the client with this error:

2021-03-20 20:05:14.37 Could not resolve placeholder ${System.getenv('BOT_KEY')}

My variable is correctly defined in the server, how can I access to it when injecting the client?


Solution

  • Micronaut ships with pre-made PropertySourceLoaders that will resolve PropertySources from different sources. You can read more on externalized configuration through the docs.

    Besides these PropertySourceLoaders, PropertySources are resolved from environment variables and are automatically injected and available for use within the ApplicationContext following the property source key syntax:

    i.e. SOME_ENVIRONMENT_VARIABLE translates to some.environment.variable

    Hence you can simply inject your HttpClient declaratively with the environment variable key translated to dot-separated-property-key syntax:

    @Client('${bot.url}')
    @Inject
    RxHttpClient httpClient