1

我正在制作一个自定义属性提供程序,以在启动时加载 Spring 云配置服务器的内容。我需要在提供程序的初始化时进行一次调用以获取这些属性,并且想使用 Mule HttpService 来为此调用创建 http 客户端,而不是创建我自己的。不幸的是,每当我尝试这个时,似乎 HttpService 尚未创建,因此一旦被引用就会抛出 NPE。

CustomConfigurationPropertiesProviderFactory.java

public class CustomConfigurationPropertiesProviderFactory implements ConfigurationPropertiesProviderFactory {

  public static final String EXTENSION_NAMESPACE = "custom-properties";
  public static final String CONFIGURATION_PROPERTIES_ELEMENT = "config";
  public static final ComponentIdentifier CUSTOM_CONFIGURATION_PROPERTIES =
      builder().namespace(EXTENSION_NAMESPACE).name(CONFIGURATION_PROPERTIES_ELEMENT).build();

  @Inject
  HttpService httpService;

  @Override
  public ComponentIdentifier getSupportedComponentIdentifier() {
    return CUSTOM_CONFIGURATION_PROPERTIES;
  }

  @Override
  public ConfigurationPropertiesProvider createProvider(ConfigurationParameters parameters,
                                                              ResourceProvider externalResourceProvider) {
    String url = parameters.getStringParameter("url");

    return new CustomConfigurationPropertiesProvider(url, httpService);
  }

}

CustomConfigurationPropertiesProvider.java

public class CustomConfigurationPropertiesProvider implements ConfigurationPropertiesProvider {

  private final static String PREFIX = "custom::";

  private Properties properties = null;

  public CustomConfigurationPropertiesProvider(String url, HttpService httpService) {
    HttpClientConfiguration.Builder builder = new HttpClientConfiguration.Builder();
    builder.setName("customProperties");
    HttpClient client = httpService.getClientFactory().create(builder.build()); //NPE here
    client.start();
    // proceed to create and execute request, then load into properties
  }

  @Override
  public Optional<ConfigurationProperty> getConfigurationProperty(String configurationAttributeKey) {
    if (configurationAttributeKey.startsWith(PREFIX)) {
      String effectiveKey = configurationAttributeKey.substring(PREFIX.length());
      if (properties != null && !properties.isEmpty()) {
        return Optional.of(new ConfigurationProperty() {
          @Override
          public Object getSource() {...}

          @Override
          public Object getRawValue() { return properties.getProperty(effectiveKey); }

          @Override
          public String getKey() { return effectiveKey; }
        });
      }
    }
    return Optional.empty();
  }
}

我需要更改什么才能正确注入此服务?

我一直在遵循这两个文档中的建议,以供参考:

4

0 回答 0