kotlingradlemicronautgradle-task

How to execute particular class method with dependency injection through gradle task?


Here is my code in build.gradle

task runDataFeeder(type:JavaExec){
    classpath = sourceSets.main.runtimeClasspath
    main = "example.core.RunMigrator"
}

And my RunMigrator class

class Migrator(@Inject val seedDataService: seedDataService) {
    fun migrate() {
        seedDataService.createZone()
    }
}

class RunMigrator {
    companion object {
        @JvmStatic
        fun main(args: Array<String>) {
           Migrator().migrate()
        }
    }
}

Note seedDataService having methods for feeding data to a database.

I am trying to run RunMigrator main method from Gradle task but don't know how to inject seedDataService through Gradle task


Solution

  • I think you should initialize the application context in order to start a DI. It works in Java:

    import io.micronaut.context.ApplicationContext;
    
    public class RunMigrator {
    
        public static void main(String[] args) {
    
            try (ApplicationContext applicationContext = ApplicationContext.run()) {
                Migrator migrator = applicationContext.getBean(Migrator.class);
                migrator.migrate();
            }
        }
    }