如何在 Spring Boot 中覆盖默认 JSON 响应
Posted
技术标签:
【中文标题】如何在 Spring Boot 中覆盖默认 JSON 响应【英文标题】:How to overwrite the default JSON response in Spring boot 【发布时间】:2015-08-30 22:13:42 【问题描述】:当控制器响应 400-BadRequest 时,我的 Spring Boot 应用程序返回低于 json 响应。
"readyState": 4,
"responseText": "\r\n \"success\" : false,\r\n \"projects\" :null,\r\n \"httpStatusCode\" : \"400\",\r\n \"message\" : \"Request Processing failed.\",\r\n \"requestErrors\" : [ \r\n \"error\" : \"platform required.\"\r\n , \r\n \"error\" : \"id required.\"\r\n , \r\n \"error\" : \"name required.\"\r\n ]\r\n",
"responseJSON":
"success": false,
"projects": null,
"httpStatusCode": "400",
"message": "Request Processing failed.",
"requestErrors": [
"error": "platform required."
,
"error": "id required."
,
"error": "name required."
]
,
"status": 400,
"statusText": "Bad Request"
但在这里我不想看到 json 元素 responseText
、status
和 statusText
,因为我的 JSON 对象本身就有这些信息。
这是我的CustomErrorAttributes
课程。
public class CustomErrorAttribute implements ErrorAttributes
@Override
public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes, boolean includeStackTrace)
Map<String, Object> errorAttributes = new LinkedHashMap<String, Object>();
errorAttributes.put("timestamp", new Date());
return errorAttributes;
@Override
public Throwable getError(RequestAttributes requestAttributes)
return new IllegalStateException("Illegal State of the request.");
Java 配置:
@Bean
public ErrorAttributes customErrorAttribute()
return new CustomErrorAttribute();
我尝试将ErrorAttributes
的自定义实现注册为@Bean
指定here
但没有运气,请任何帮助。谢谢。
【问题讨论】:
你能把你配置ErrorAttributes
的代码贴出来吗?
您好@geoand 更新了ErrorAttributes
实施的问题。
你配置了ErrorAttributes
类型的bean吗?
【参考方案1】:
您需要让 Spring 了解您的 CustomErrorAttribute
实现。
只需添加一个配置类(或简单地将@Bean
部分添加到您现有的 Spring 配置类之一),例如:
@Configuration
public class MvcErrorConfig
@Bean
public CustomErrorAttribute errorAttributes()
return new CustomErrorAttribute();
一切都开箱即用。
This 部分文档包含所有详细信息。
相关的 Spring Boot 自动配置类是ErrorMvcAutoConfiguration
【讨论】:
我确信CustomErrorAttribute
是 Spring 感知的,因为我能够自动装配它。 githug 链接到我的项目github.com/lovababu/SpringBootExample
好的,我运行项目并回复你
项目中的错误处理对我来说是开箱即用的。 CustomErrorAttribute
类被 Spring 正确使用。也许你应该执行gradle clean
看看会发生什么
我还应该提到,当我通过 IDE 或使用 Gradle
运行主类时,代码可以正常工作。
你的意思是说,如果没有前面提到的那些 json 元素,你会得到响应吗?我确实通过 IDE 清理并运行了 main,但没有运气仍然相同的响应。以上是关于如何在 Spring Boot 中覆盖默认 JSON 响应的主要内容,如果未能解决你的问题,请参考以下文章