如何在子命令 picocli 中使用父命令

问题描述

我使用 picocli 并且我有命令 connect db 看起来像

@CommandLine.Command(
    name = "database",defaultValueProvider = PropertiesDefaultProvider::class,scope = CommandLine.ScopeType.INHERIT
)
open class DataSource : Runnable {
    @CommandLine.Option(names = ["-ho","--host"],description = ["host"])
    var host: String? = null

    @CommandLine.Option(names = ["-p","--port"],description = ["port database"])
    var port: String? = null

    @CommandLine.Option(names = ["-d","--database"],description = ["database"])
    var database: String? = null

    @CommandLine.Option(names = ["-u","--username"],description = ["username of database"])
    var username: String? = null

    @CommandLine.Option(names = ["-w","--password"],description = ["password of database"])
    var password: String? = null

    override fun run() {

    }

    fun connectDatabase() {
        Database.connect(this.connectDB())
    }

    fun connectDB(): DataSource {
        val config = HikariConfig()
        config.jdbcUrl = "jdbc:postgresql://${host}:${port}/${database}"
        config.username = username
        config.password = password
        config.driverClassName = "org.postgresql.Driver"
        return HikariDataSource(config)
    }

现在我有命令:StudentService

@CommandLine.Command(name = "studentService",description = arrayOf("StudentService"))
class StudentService() : Runnable,DataSource() {

    @CommandLine.Parameters(arity = "1..*",index = "0")
    var name: String? = null

    @Spec
    protected var spec: CommandSpec? = null

    override fun run() {
        getStudentService()
    }

    fun getStudentService() {
        //I want call command connect database here
        transaction() {
            //do something logic
        }
    }
}

现在我想要当我调用命令 studentService 时,它​​会自动 connectDb 。如果用户没有指定主机、端口或用户名,它总是从我的属性中获得认值。如果用户特定的主机,端口它自动解析。怎么做 ?当我只调用命令时:数据库?这行得通。如果我不输入任何信息,它会获得数据库认值吗?但我不知道将命令数据库集成到 studentService

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)