Skip to content
Advertisement

Micronaut – Create a bean without creating ApplicationContext

I have a Micronaut declarative HTTP client written using @client annotation. I want to call this while starting micronaut app before creating the ApplicationContext itslef.

HttpClient : SampleHttpClient.java

import io.micronaut.http.HttpResponse;
import io.micronaut.http.MediaType;
import io.micronaut.http.annotation.Get;
import io.micronaut.http.annotation.Header;
import io.micronaut.http.client.annotation.Client;

@Client("http://127.0.0.1:8200")
@Header(name = "X-Vault-Token", value = "hvs.CEGT7cKyMA8wsDbgKZqxC34q")
public interface SampleHttpClient {
    @Get(value = "/v1/kv/data/KMS", produces = MediaType.APPLICATION_JSON)
    HttpResponse<String> getVaultSecret();
}

Application.java (Main class)

import io.micronaut.context.ApplicationContext;
import io.micronaut.runtime.Micronaut;

public class Application {
    public static void main(String[] args) {

        // Following code works perfect. I am creating context here. But I dont want to do this
        SampleHttpClient client = Micronaut.run(Application.class, args).
                getBeansOfType(SampleHttpClient.class).stream().findFirst().get();
        System.out.println("Response Body ="+client.getVaultSecret().body());
   
        // How do we get the instance of SampleHttpClient without using Micronaut's dependency 
injection process???

    }
}

Advertisement

Answer

I want to call this while starting micronaut app before creating the ApplicationContext itslef.

Micronaut doesn’t provide a mechanism to support that. You could write your own thing that instantiates the beans, but that is a large undertaking. You would be writing your own bean container.

Advertisement