我想尝试new rule based configuration in Gradle来配置我的插件。插件的目的是将数据上传到云存储,例如Google Drive或S3。我需要为用户要使用的每个存储配置。所以,我想要实现的是:

model {
    backup { // this is a container for all storages I want to support
        googleDrive {
            clientId = ''
            clientSecret = ''
            accessToken = ''
            refreshToken = ''
        }

        s3 {
           // S3 specific config (like API keys)
        }
    }
}

在我的插件中,我为backup元素配置规则源:
class BackupPlugin implements Plugin<Project> {

    static class Rules extends RuleSource {
        @Model
        void backup(BackupPluginExtension backupModel) {}
    }
}

@Managed
interface BackupPluginExtension {
    GoogleDrive getGoogleDrive()

    void setGoogleDrive(GoogleDrive googleDrive)
}

@Managed
interface GoogleDrive {
    String getClientId()

    void setClientId(String clientId)

    String getClientSecret()

    void setClientSecret(String clientSecret)

    String getAccessToken()

    void setAccessToken(String accessToken)

    String getRefreshToken()

    void setRefreshToken(String refreshToken)
}

但是,这样说是行不通的:Could not find method googleDrive() for arguments [build_8w85xu7hrz3atgeg839d33hzl$_run_closure1_closure2_closure3@1b06ac95] on root project 'test'.。看起来它尝试调用backup内部的方法,而不配置嵌套的bean。

那么,正确的语法是什么?

我知道命名集合,但问题是如何配置自定义bean层次结构。

最佳答案

在玩了一段时间之后,似乎使googleDrive为只读(例如,通过删除setGoogleDrive() setter)可以解决您的问题(运行gradle model时,我会获得BUILD SUCCESSFUL)。

经过一些小的修改(使用@Mutate而不是Plugin.apply),它看起来像这样:

apply plugin: BackupPlugin

class BackupPlugin extends RuleSource {
    @Model
    void backup(BackupPluginExtension backupModel) {
    }

    @Mutate void createTasks(ModelMap<Task> tasks, BackupPluginExtension model) {
        tasks.create("backup") {
            doLast {
                // ... do stuff
                println "googleDrive.clientId = ${model.googleDrive.clientId}"
            }
        }
    }
}

@Managed
interface BackupPluginExtension {
    GoogleDrive getGoogleDrive()

//    void setGoogleDrive(GoogleDrive googleDrive)
}

@Managed
interface GoogleDrive {
    String getClientId()

    void setClientId(String clientId)

    String getClientSecret()

    void setClientSecret(String clientSecret)

    String getAccessToken()

    void setAccessToken(String accessToken)

    String getRefreshToken()

    void setRefreshToken(String refreshToken)
}

model {
    backup { // this is a container for all storages I want to support
        googleDrive  {
            clientId = 'someId'
            clientSecret = ''
            accessToken = ''
            refreshToken = ''
        }

    }
}

在此运行gradle backup将打印googleDrive.clientId = someId

10-08 06:17