groovy - 从 Spring Boot 渲染 GORM 类

标签 groovy grails-orm spring-boot

我正在尝试编写一个简单的 Spring Boot Controller 来呈现 GORM 实例并失败。

这是我的代码的缩短版本:

@RestController
@RequestMapping("/user")
class UserController {
    @RequestMapping(value='/test', method=GET)
    User test() {
        return new User(username: 'my test username')
    }
}

我收到以下错误消息:
Could not write JSON: No serializer found for class org.springframework.validation.DefaultMessageCodesResolver and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) ) (through reference chain: users.domain.User["errors"]->grails.validation.ValidationErrors["messageCodesResolver"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class org.springframework.validation.DefaultMessageCodesResolver and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) ) (through reference chain: users.domain.User["errors"]->grails.validation.ValidationErrors["messageCodesResolver"])
该错误似乎是由 GORM 注入(inject)的额外属性引起的。对此提出的解决方案是什么?这最终会在gorm-hibernate4-spring-boot 中解决吗? ?我是否应该简单地禁用 SerializationFeature.FAIL_ON_EMPTY_BEANS (我对 jackson 没有很多经验,所以我不完全确定这可能会产生什么副作用)?我应该使用 jackson 的注释来解决问题吗?还有其他选择吗?

最佳答案

我找到了一种使用以下代码消除错误的方法:

@Component
class ObjectMapperConfiguration implements InitializingBean {

    @Autowired
    ObjectMapper objectMapper

    @Override
    void afterPropertiesSet() {
        def validationErrorsModule = new SimpleModule()
        validationErrorsModule.addSerializer(ValidationErrors, new ErrorsSerializer())
        objectMapper.registerModule(validationErrorsModule)
    }

}

class ErrorsSerializer extends JsonSerializer<ValidationErrors> {
    @Override
    void serialize(ValidationErrors errors, JsonGenerator jgen, SerializerProvider provider) {
        jgen.writeStartObject()
        jgen.writeEndObject()
    }
}

显然,这个解决方案远非完美,因为它只是消除了所有验证错误,但现在对我来说已经足够了。我很确定 Spring Boot 团队最终将不得不解决这个问题,因为 GORM 对象也正在使用一些内部 Hibernate 属性进行序列化,例如 attached .我不接受这个答案,因为它在大多数情况下都不是可接受的解决方案,它基本上只是压制了异常。

关于groovy - 从 Spring Boot 渲染 GORM 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24576785/

相关文章:

spring-boot - spring boot 数据 redis 存储库 @Id 注释 vs jpa 存储库 @Id

java - Groovy SQL 导入错误。即使包含在内也找不到属性

concurrency - GPars 锁返回 null

grails - 在 JDBC 设置之后尝试启动 Grails 时出错

grails - 是否可以为 grails 域对象保存一个特定的 id?

mongodb - GORM 查询多个集合

带有 map 的 Groovy 多重赋值

Grails 应用程序中的 Hibernate 二级缓存

java - 访问应用程序特定的 url 时,Spring security oauth 中出现 403 错误(access_token 有效且 csrf 已禁用)

java - Spring Boot JPA @Query 更新不起作用