Micronaut自动转换HTTP请求参数

Micronaut automatic conversion of HTTP request parameters

我目前正在努力尝试设置 micronaut,以便自动将参数从 http 请求 uri 转换为 pojos。

具体来说,我想实现这样的目标:

@Controller
public class FooBarBazController {

    @Get("/{foo}/{bar}")
    public Baz doSomething(Foo foo, Bar bar) {
        return new Baz(foo, bar);
    }

}

假设 FooBar 可以从字符串值构造。

我从服务器得到的唯一响应是

{
  "_links": {
    "self": {
      "href": "/forever/young",
      "templated": false
    }
  },
  "message": "Required argument [Foo foo] not specified",
  "path": "/foo"
}

我已经尝试过以下方法:

None 似乎有帮助,我在网上找不到任何与我的问题相似的参考资料。

有谁知道如何指示框架执行自动转换和绑定?

谢谢。

如果您能够使用 1.0.3 版本中的 newly introduced @PathVariable,您就万事大吉了。

对于 Micronaut 1.3,唯一需要做的就是为 FooBar:

定义一个 TypeConverter
@Singleton
public class FooTypeConverter implements TypeConverter<String, Foo> {
    @Override
    public Optional<Foo> convert(String fooString, Class<Foo> targetType, ConversionContext context) {
        return new Foo(fooString);
    }
}

...

@Singleton
public class BarTypeConverter implements TypeConverter<String, Bar> {
    @Override
    public Optional<Bar> convert(String barString, Class<Bar> targetType, ConversionContext context) {
        return new Bar(barString);
    }
}

就是这样。

在你的控制器中,你可以像 Micronaut 知道的任何其他类型一样使用 FooBar

@Get("/foo/{foo}")
public HttpResponse<FooResponse> getFoo(@PathVariable Foo foo) {
    ...
}

...

@Get("/bar/{bar}")
public HttpResponse<BarResponse> getBar(@PathVariable Bar bar) {
    ...
}