您如何在 Spring Boot 2.0 执行器端点的“@WriteOperation”中使用“@Selector”?

How do you use `@Selector` in `@WriteOperation` in Spring Boot 2.0 actuator endpoint?

我正在使用以下 class 实现自定义端点:

@Component
@Endpoint(id = "bootstrap")
public class BootstrapUrlEndpoint {

  private final URL bootstrapUrl;

  @Autowired
  public BootstrapUrlEndpoint(URL bootstrapUrl) {
    this.bootstrapUrl = bootstrapUrl;
  }

  @ReadOperation
  public Map<String, String> getBootstrapUrl() {
    Map<String, String> result = new HashMap<>();
    result.put("bootstrap_url", bootstrapUrl.toExternalForm());
    return result;
  }

  @WriteOperation
  public void setBootstrapUrl(@Selector String property, String value) throws MalformedURLException {
    System.out.println(String.format(">>> Setting  %s = %s", property, value));
  }
}

这都是"works as intended"没有@Selector注解;省略它并发送一个 POSThttp://localhost:8080/actuator/bootstrap 与:

{
  "value": "http://localhost:27017/tables/application"
}

按预期调用方法。

但是,我无法使 "selector" 工作;我在启动日志中看到它已注册为有效端点:

Mapped "{[/actuator/bootstrap/{arg0}],methods=[POST],consumes=[application/vnd.spring-boot.actuator.v2+json || application/json]}" onto public org.reactivestreams....ava.util.Map<java.lang.String, java.lang.String>)

不幸的是,用 POST /actuator/bootstrap/myprop 和同一个主体调用它,会产生一个 400 Bad Request 而没有错误日志或错误消息。

我一直在寻找更多信息和可能的示例:我能找到的唯一相关(但是,唉,不完整)示例是 this article - 有人知道我的代码中缺少什么吗?

提前致谢!

我刚刚 运行 遇到了和你一样的问题,顺便说一句,有点疯狂。

但是我发现问题与@Selector注释的参数的参数命名有关。

如果您将您的变量 "property" 命名为 "arg0",一切都会起作用:

public void setBootstrapUrl(@Selector String arg0, String value)

是的,我知道这有点奇怪,但我在这个 article 中找到了一些关于编译 类.

时嵌入参数的信息

在参数中使用我自己的名字,我仍然没有真正做到这一点。

Angel Pizano 建议的解决方法确实解决了这个问题,但这里有一个更好的解决方案:为 maven 编译器插件启用参数标志:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <configuration>
        <compilerArgs>
            <arg>-parameters</arg>
        </compilerArgs>
    </configuration>
</plugin>

这里有一个相关的话题:https://github.com/spring-projects/spring-boot/issues/11010

事实上,这里的两种解决方案都可以工作,但是从 3.6.2 版开始,maven-compiler-plugin 支持新的配置元素 'parameters',您必须将其设置为 'true'.

这会为方法反射生成一些额外的元数据,spring 可以在启动时使用这些元数据来正确绑定您的参数。参见 maven-compiler-plugin documentation

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.6.2</version>
            <configuration>
                <parameters>true</parameters>
            </configuration>
        </plugin>