如何在 dropwizard 1.0.0 中获取 applicationContextPath

How to get applicationContextPath in dropwizard 1.0.0

我们在 yml 文件中使用服务器配置,如下所示

server:
type: simple

connector:
  type: http
  port: 8061

applicationContextPath: /administration
adminContextPath: /admin

#disable the registration of default Jersey ExceptionMappers
registerDefaultExceptionMappers: false

我想在启动 dropwizard 服务时得到 "applicationContextPath"。

我正在尝试使用

获取它
environment.getApplicationContext().getContextPath();

但我得到的是“/”,即默认值。有没有办法弄到这个。

这对我有用:

@Override
    public void run(CustomAppConfiguration customAppConfiguration , Environment environment) throws Exception {
DefaultServerFactory factory = (DefaultServerFactory) customAppConfiguration .getServerFactory();
System.out.println("CONTEXT PATH: "+factory.getApplicationContextPath());
...
}

如果它在您的配置文件中,而您只想读取存在于您的 config.yml 中的值,那么我建议将其作为您的 Configuration class 的一部分。无论 dropwizard 是否在内部以特殊方式使用和处理这些 key/values,您的配置中的值始终可以通过这种方式访问​​。

以下内容在 dropwizard 1.0.0 中对我有效:

MyApp.java:

public class MyApp extends Application<MyConfig> {
//...
@Override
public void run(MyConfig configuration, Environment environment) throws Exception {
    System.out.println(configuration.contextPath);
//...

MyConfig.java

public class MyConfig extends Configuration {
//...
   @JsonProperty("applicationContextPath")
   public String contextPath;
//...

为了获取 applicationContextPath,我们需要从 Configuration 获取 ServerFactory 并将其解析为 SimpleServerFactory,如下所示:

((SimpleServerFactory) getConfiguration().getServerFactory()).getApplicationContextPath()

如果我正确理解了你的问题,你可以在 Dropwizard 版本 1.3.8 中做什么,如果你使用简单的服务器(没有 https ) 你可以通过以下方式获取applicationContextPath:

server:
  type: simple
  rootPath: /*
  applicationContextPath: /administration
  adminContextPath: /admin
  connector:
    type: http
    port: 8080

有关 rootPath 的更多信息可以在 Dropwizard Configuration Reference 中找到。所以如果你想访问:

  1. Application REST 端点/books(这是 GET 的值, POST 或您的一种资源 class 方法中的类似注释)您可以 像这样输入 URL http://localhost:8080/administration/books
  2. Metrics(只能通过 admin 上下文路径访问),然后像这样创建 URL:
    http://localhost:8080/admin/metrics

希望对您有所帮助。干杯!