Home:ALL Converter>How to use Micronaut & depenency injection in a single-file Groovy script?

How to use Micronaut & depenency injection in a single-file Groovy script?

Ask Time:2021-02-07T11:20:09         Author:andreoss

Json Formatter

I want to use Micronaut from a Groovy script. It seems that annotations such as @Inject and @PostConstruct are not processed.

Here is the code I tried:

#!/usr/bin/env nix-shell
#!nix-shell -i groovy
@Grapes([
    @Grab('ch.qos.logback:logback-classic'),
    @Grab('io.micronaut:micronaut-runtime')
])

package org.sdf // NPE without package

import io.micronaut.runtime.Micronaut
import javax.inject.*
import javax.annotation.*

@Singleton
class Component {

}

@Singleton
class App implements Runnable {
    @Inject
    Component comp

    @Override
    @PostConstruct
    public void run() {
        // Never runs
        assert this.comp != null
        assert false
    }
}

static void main(String... args) {
    Micronaut.run(App, args);
}

It doesn't run post-construct method and logs this:

22:17:43.669 [main] DEBUG i.m.context.DefaultBeanContext - Resolved bean candidates [] for type: interface io.micronaut.runtime.EmbeddedApplication
22:17:43.671 [main] INFO  io.micronaut.runtime.Micronaut - No embedded container found. Running as CLI application

How can I use Micronaut with dependency injection in a single-file Groovy script?

Author:andreoss,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/66084240/how-to-use-micronaut-depenency-injection-in-a-single-file-groovy-script
yy