【问题标题】:Request Scoped bean cannot use in Response body [Spring Boot]请求范围 bean 不能在响应正文中使用 [Spring Boot]
【发布时间】:2019-09-23 18:54:37
【问题描述】:

我有一个 Request scoped(prototype) bean 作为 Rest Controller 的 Response 并得到 Exception ,但不工作

我在属性文件上尝试了 spring.jackson.serialization.FAIL_ON_EMPTY_BEANS=false,如错误消息 “类型定义错误:[简单类型,类 org.springframework.context.expression.StandardBeanExpressionResolver];嵌套异常是 com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class org.springframework.context.expression.StandardBeanExpressionResolver 并且没有发现创建 BeanSerializer 的属性(为避免异常,禁用 SerializationFeature.FAIL_ON_EMPTY_BEANS)(通过参考链:com .epic.dcms.kyc.beans.MainResponse$$EnhancerBySpringCGLIB$$82085c99[\"targetSource\"]->org.springframework.aop.target.SimpleBeanTargetSource[\"beanFactory\"]->org.springframework.beans.factory .support.DefaultListableBeanFactory[\"beanExpressionResolver\"])",

没有工作,然后存在循环依赖并引发异常

@RequestScope 注释更改为 @scope 注释也没有解决问题

我注意到只有当 MainResponse 用作响应时才会出现此异常。

  Bean
        @RequestScope
        @Component
        public class MainResponse implements Serializable{
        //fields and getters and setters
        }

  Controller class
         @PostMapping("/uploadFile")
            public MainResponse uploadFile(@RequestParam("file") MultipartFile file) throws FileStorageException {
                String fileName = fileStorageService.storeFile(file);

                response.putPayLoad(true,"fileName",fileName)
                        .putPayLoad("ContentType",file.getContentType())
                        .putPayLoad("size",file.getSize());

                return response;
            }

当我从 MainResponse bean 中删除 @RequestScope 时,它​​工作正常,知道如何解决这个问题吗??

【问题讨论】:

  • 为什么 MainResponse 是一个 bean?
  • 它是Request scoped (prototype) bean,所以它是由框架管理的,任何建议都非常感谢。
  • 通常请求和响应对象不由 Spring 管理,因为它们没有生命周期。

标签: java spring-boot requestscope


【解决方案1】:

您的响应类不需要用“@RequestScope”标记,数据绑定将由框架自己管理。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-21
    • 1970-01-01
    • 2017-04-25
    • 1970-01-01
    • 2011-08-15
    • 2011-08-19
    • 2011-04-19
    相关资源
    最近更新 更多