我想知道。我可以做到这一点吗?在我的Dropwizard config.yml中,我想扩展databaseConfiguration类,以便向config.yml添加另一个属性,如下所示

配置文件

database
  driverClass: org.postgresql.Driver
  user: user1
  password: password
  exampleProperty: property1 (Tried a few other permutations)


假设有一个DatabaseConfiguration类,该类具有带有getter的字段以及driverClass,用户,密码等的注释

public class AppConfiguration extends Configuration {
  @Valid
  @NotNull
  @JsonProperty
  private DatabaseConfiguration database = new DatabaseConfiguration();

  public DatabaseConfiguration getDatabaseConfiguration() {
    return database;
  }

  @Valid
  @NotNull
  @JsonProperty
  private ExtendedDatabaseConfiguration extDatabase;
  public ExtendedDatabaseConfiguration getExtendedDatabaseConfiguration() {
     return extDatabase;
  }

  public class ExtendedDatabaseConfiguration extends DatabaseConfiguration {
  @Valid
  @NotNull
  @JsonProperty
  private String exampleProperty;
  public String getExampleProperty() { return exampleProperty; };
  }


主类Server.java通过调用将ExtendedDatabaseConfiguration传递给Hibernate Bundle(以前传递给DatabaseConfiguration)

    private final CustomHibernateBundle<AppConfiguration> hibernateBundle = new CustomHibernateBundle<AppConfiguration>() {
    @Override
    //Giving the subclass holding the new database property to the CustomHibernateBundle
    public DatabaseConfiguration getDatabaseConfiguration(AppConfiguration configuration) {
        return configuration.getExtendedDatabaseConfiguration();
    }
};
    SimpleModule simpleModule = new SimpleModule();
    simpleModule.addAbstractTypeMapping(DatabaseConfiguration.class, ExtendedDatabaseConfiguration.class);
    bootstrap.getObjectMapperFactory().registerModule(simpleModule);


这一切都是为了让CustomHibernateBundle随便使用此字段。

无论我尝试了什么,我都会收到错误jackson.databind.exc.UnrecognizedPropertyException或得到以下内容

Exception in thread "main" com.yammer.dropwizard.config.ConfigurationException: powaaim.yml has the     following errors:
* extDatabase may not be null (was null)
* exampleProperty may not be null (was null)


只是要注意。我无权修改DatabaseConfiguration,但可以对其进行扩展。想知道是否可以实现这一点,以便我可以通过这种方法定义更多的数据库配置属性。

还是有一种更简单的方法?

最佳答案

您应该能够扩展DatabaseConfiguration-我认为您刚刚添加了解析器现在期望的额外配置字段(尽管我不确定有关丢失的key的警告来自何处)。尝试以下配置类:

public class AppConfiguration extends Configuration {
  @Valid
  @NotNull
  @JsonProperty
  private ExtendedDatabaseConfiguration database = new ExtendedDatabaseConfiguration();

  public ExtendedDatabaseConfiguration getDatabaseConfiguration() {
    return database;
  }

  static class ExtendedDatabaseConfiguration extends DatabaseConfiguration {
    @Valid
    @NotNull
    @JsonProperty
    private String exampleProperty;
    public String getExampleProperty() { return exampleProperty; };
  }
}

关于java - 在Dropwizard yaml中找不到DatabaseConfiguration子类中的property(分层问题),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23839506/

10-09 10:08