javapackagemicronautapplicationcontext

Micronaut ApplicationContext creation for package


In Spring, it is easy to create ApplicationContext that uses only classes defined in a given package. How to achieve that in Micronaut?

I write:

ApplicationContext context =
    ApplicationContext.builder()
        .args(args)
        .packages("org.kalamity.server")
        .start();

context.getBean(MessageEventListener.class);

But beans from foreign packages are created and injected. I know, that Micronaut works on compile time, so it might be completely impossible.


Solution

  • When looking into io.micronaut.context.DefaultApplicationContextBuilder#build, we'll find this:

    if (!packages.isEmpty()) {
        for (String aPackage : packages) {
            environment.addPackage(aPackage);
        }
    }
    

    Doc for Environment#addPackage says:

    Add an application package. Application packages are candidates for scanning for tools that need it (such as JPA or GORM). Params: pkg – The package to add Returns: This environment

    Hence, I believe it's not possible to limit context using a list of packages like in the question with Micronaut out-of-the-box.

    However, you may use @Requires annotation to load parts of the context. https://docs.micronaut.io/latest/guide/#conditionalBeans

    Source code from Micronaut 3.2.1