0

我使用 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

4

0 回答 0