如何在Spring @RestController中映射多个bean?

时间:2017-06-15 06:19:26

标签: java spring spring-mvc

如何在@RestController中映射多个bean

我正在使用spring-web-4.3.8.RELEASE.jar

我尝试了一切: @RequestParam @RequestBody,@ RequestAttribute,@ RequestPart 但没有任何作用......

package com.example.demo;

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class RestService {

    @RequestMapping(value = "demo", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    public Object[] demo(Foo foo, Bar bar) {
        return new Object[]{foo, bar};
    }

    public static class Bar {
        public Long id;
        public String bar;
    }

    public static class Foo {
        public Long id;
        public String foo;
    }
}

我的(已编码)有效负载是:

  

富=%7B%22id%22%3A123%2C%22foo%22%3A%22foo1%22%7D&安培;栏=%7B%22id%22%3A456%2C%22bar%22%3A%22bar1%22 %7D

解码的有效负载:

  

富= { “ID”:123, “foo” 的: “foo1”}&安培;栏= { “ID”:456, “酒吧”: “BAR1”}

请求标题:

  

内容类型:application / x-www-form-urlencoded

使用上面的代码,它返回:

  

[{ “ID”:空, “foo” 的日期null},{ “ID”:NULL, “酒吧”:空}]

但我想要的是:

  

[{ “ID”:123, “foo” 的: “foo1”},{ “ID”:456, “酒吧”: “BAR1”}]

由于

1 个答案:

答案 0 :(得分:0)

您正在RestController中创建静态内部类。 Spring无法使用上述bean自动映射接收到的请求中的属性。请在单独的包或外部控制器中定义您的bean。然后,您将能够使用@RequestBody映射它。

            @RestController
            public class RestService {

                @RequestMapping(value = "demo", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
                public Object[] demo(@RequestBody FooBar foobar) {
                      // your custom work
                }
            }


                public class Bar {
                    public Long id;
                    public String bar;
                }

                public class Foo {
                    public Long id;
                    public String foo;
                }

// created wrapper as @RequestBody can be used only with one argument.
                public class FooBar {
                      private Foo foo;
                      private Bar bar;
                }

请参阅requestBody with multiple beans

还要确保请求参数名称与bean的属性匹配。(即Foo和Bar)。