grails - Grails 4:自定义域模型编组器在 Grails 4 上不起作用
问题描述
我目前的问题是我创建的自定义对象编组器,因为 grails 2.4.5到 grails 3.3.0不适用于 grails 4.0.0。Grails 4 默认响应域模型而不是我创建的自定义。
以下是我拥有的代码。请查看,如果您发现有问题,请让我知道伙计们,如果您能帮助我,我将很高兴。
ResponseSender.groovy
package com.problem.solve.common
import org.springframework.http.HttpStatus
trait ResponseSender {
void sendResponse() {
render status: HttpStatus.NO_CONTENT
}
void sendResponse(def responseData) {
respond (responseData)
}
void sendResponse(HttpStatus status, def responseData) {
response.status = status.value()
respond (responseData)
}
}
此ResponseSender.groovy特征在控制器上实现。
MarshallerInitializer.groovy
package com.problem.solve.marshaller
class MarshallerInitializer {
CustomObjectMarshallers customObjectMarshallers
void initialize() {
customObjectMarshallers.register()
}
}
这个MarshallerInitializer.groovy将在 bootstrap 初始化时被调用。
package com.problem.solve.marshaller
class CustomObjectMarshallers {
List marshallers = []
void register() {
marshallers.each {
it.register()
}
}
}
这个CustomObjectMarshallers.groovy将注册所有编组器。
UserMarshaller.groovy
package com.problem.solve.marshaller.marshalls
import com.problem.solve.security.User
import grails.converters.JSON
class UserMarshaller {
void register() {
JSON.registerObjectMarshaller(User) { User user ->
return [
id: user.id,
fullName: user.fullName,
username: user.username,
emailAddress: user.emailAddress,
roles: user.authorities.authority,
dateCreated: user.dateCreated,
lastUpdated: user.lastUpdated,
_entityType: 'User'
]
}
}
这个UserMarshaller.groovy是一个示例域模型,我想将它从域模型转换为 json 响应。
资源.groovy
import com.problem.solve.marshaller.CustomObjectMarshallers
import com.problem.solve.marshaller.MarshallerInitializer
import com.problem.solve.marshaller.marshalls.*
// Place your Spring DSL code here
beans = {
customObjectMarshallers(CustomObjectMarshallers) {
marshallers = [
new UserMarshaller()
]
}
marshallerInitializer(MarshallerInitializer) {
customObjectMarshallers = ref('customObjectMarshallers')
}
}
此设置的问题不适用于 grails 4,但此设置适用于 grails 2.4.5 和 grails 3.3.0。
我真的需要你们的帮助。
太感谢了 :)
解决方案
我通过创建 DomainModelResponseDto 作为响应域模型来解决这个编组器问题。
例子:
class UserResponseDto {
String id
String username
String email
UserResponseDto(User user) {
id = user.id
username = user.username
email = user.email
}
}
推荐阅读
- arrays - 包含跨两个字段的值对 - Groovy
- c# - 无法添加对单元测试项目的引用
- swift - 为什么我在第二个例子中得到了保留圈?
- arrays - 在 for 循环中扩展数组(文件列表)
- jquery - typeahead.js 返回“空白”数据集
- r - 子集嵌套列表
- php - Laravel Eloquent - 使用关系将查询组合成单个查询
- node.js - 如何使用 IAP 和 People API 获取用户的 Google 帐户照片?(首选 NodeJS)
- javascript - 节点缓存需要很长时间才能在 aws elasticbeanstalk 上获取大数据
- c# - 如果 DesiredCapabilities 在 Selenium 3+ 中已经过时,那么在移动 Web 测试中使用什么来代替?