【问题标题】:Inject property value into annotation field将属性值注入注释字段
【发布时间】:2019-04-30 17:01:43
【问题描述】:

我正在开发我的 rest API,我想要一个动态的端点列表。我正在使用以下方法:

@Controller("/")
public class Resource {

    @PostMapping(path = {"request1", "request2"})
    public Mono<ResponseEntity> postData(ServerHttpRequest request) {
        return Mono.fromSupplier(() -> ResponseEntity.ok().build());
    }
}

所以我想知道是否可以从属性中动态检索 PostMapping 的路径字段的值?

提前致谢

【问题讨论】:

  • 注解变量必须是编译时常量,所以不能在其中注入任何变量。为什么不创建通配符端点 a-la @PostMapping(value = "/{id}") 并使用 @PathVariable?然后您可以过滤掉不在您的 application.properties 中的端点。
  • 直接在控制器中?它也可以,但我认为有一个可能的解决方案,就像我提出的那样
  • 是的。您可以使用@Value 注释,例如:@Value("${helloworld.endpoint}") String endpoint;
  • 实际上,它并不能解决我的问题,因为在注释字段中我只能添加常量
  • 见下面我的回答。希望有帮助

标签: spring spring-boot spring-webflux spring-web


【解决方案1】:

试试这个:

@RestController
public class Resource {
    @Value("${helloworld.endpoints}") String endpoints = "";

    @GetMapping(value = "/maybe/{wildcard}")
    public Mono<ResponseEntity> post(@PathVariable(value = "wildcard") String path) {
        boolean ok = Arrays.asList(endpoints.split(";")).contains(path);
        if (ok)
            return Mono.fromSupplier(() -> ResponseEntity.ok().build());
        else
            return Mono.fromSupplier(() -> ResponseEntity.notFound().build());
    }
}

application.properties:

helloworld.endpoints=request1;request2;request3

【讨论】:

    猜你喜欢
    • 2015-07-03
    • 2019-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-31
    • 1970-01-01
    相关资源
    最近更新 更多