【问题标题】:Defining a Grails 3.0 plugin domain class to be extendable将 Grails 3.0 插件域类定义为可扩展的
【发布时间】:2015-08-28 05:00:23
【问题描述】:

在开发 Grails 3.0 插件时:

  1. 应如何定义域以便应用程序可以使用插件对其进行扩展?
  2. 插件如何引用扩展类的实例?

例如,一个安全插件可以有如下类:

User.groovy

package com.example.plugins.security

class User {

   String  email
   String  hash
   Boolean enabled = true

}

SecurityService.groovy

package com.example.plugins.security

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder

class SecurityService {

   def authenticate(String email, String password) {
      def user = User.findByEmail(email)  //instance of BookstoreUser???
      def encoder = new BCryptPasswordEncoder()
      return user && encoder.matches(password, user.hash) ? user : null
      }

}

应用程序将具有如下域:

grails-app/domain/com/example/bookstore/BookstoreUser.groovy

package org.example.bookstore

import org.bson.types.ObjectId
import org.example.plugins.security.User

class BookstoreUser extends User {

   ObjectId id
   String   firstName
   String   lastName

   static mapWith = "mongo"

}

其余代码在:
https://github.com/center-key/bookstore

【问题讨论】:

    标签: grails groovy grails-plugin grails-domain-class grails-3.0


    【解决方案1】:

    应该如何定义一个域,以便它可以由 使用插件的应用程序?

    与定义任何其他域类的方式相同。在grails-app/domain/下声明Groovy源文件。

    插件如何引用扩展类的实例?

    您在问题中显示的代码可以正常工作。

    package com.example.plugins.security
    
    class SecurityService {
    
       def disableUser(User user) {  //the instance should be a BookstoreUser
              user.enabled = false
              user.save()
          }
    }
    

    如果应用程序编写了像BookstoreUser 这样的类来扩展您的User 类,则可以将BookstoreUser 的实例传递到您的disableUser 方法中,并且该方法的行为可能与您预期的一样。该方法会将enabled 属性设置为false,然后保存更新的实例。

    【讨论】:

    • 我的错……disableUser() 的例子过于简单化了。我用更有趣的authenticate() 方法更新了问题,并且没有传入user服务 如何知道BookstoreUser 上的findByEmail 而不是User
    • My bad... the disableUser() example was overly simplistic. - 取决于问题中不存在的其他一些因素(例如系统中是否有其他User 类型并且email 在它们之间是唯一的)您展示的解决方案将可能工作。我不得不对你的问题投反对票。发布问题,获得专门针对该问题的答案,然后更改问题以提出其他问题,这是不负责任的。你在浪费那些自愿帮助你的人的时间。如果您有一个单独的问题应该作为单独的问题提出。
    • 示例代码只是为了添加对问题的具体引用。问题仍然存在:How does the plugin reference instances of the extended class?我没有编辑问题。利用示例代码中的技术性而不实际回答问题不会使未来尝试构建 Grails 插件的读者受益。我非常刻意地措辞这个问题,希望对 Grails 社区有帮助。
    • Exploiting a technicality in the example code but not actually answering the question will not benefit future readers trying to build Grails plugins. - 我不知道你是否断言这个答案能做到这一点。可能是我误解了这个问题。看来您可能会问如何将User 类型的引用指向堆上的一个对象,该对象是扩展User 的其他类的实例。如果这就是您要问的,那么上面的答案可以解决这个问题。如果这不是您要问的,我很抱歉无法提供帮助。
    • 通常无法将实例传递给插件服务,例如当插件服务需要创建新实例或搜索数据库以查找现有实例时。对于安全插件,注册新用户和在登录时验证用户身份都是如此。对于仍然对此感兴趣的任何人(我认为应该是几乎所有 Grails 插件开发人员),这是一个包含示例插件和一个测试应用:github.com/dpilafian/grails-plugin-experiment
    猜你喜欢
    • 1970-01-01
    • 2011-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-04
    • 2011-10-13
    • 1970-01-01
    相关资源
    最近更新 更多