Add custom converter before manully binding properties using EnvironmentAware : Springboot

68 views Asked by At

I need to dynamically add beans to my application for which I need to bind some properties from application.yml (some properties depend on gcp secret manager)

Below is the custom binding and bean registration.

@Component
public class PropertiesRegistrar implements BeanDefinitionRegistryPostProcessor, EnvironmentAware {

private ConfigProperties configProperties

@Override
  public void setEnvironment(@NotNull Environment environment) {
    configProperties = Binder.get(environment)
        .bind("custom-props", ConfigProperties.class)
        .orElseThrow(() -> new InvalidConfigurationException("No config properties found"));
  }

  @Override
  public void postProcessBeanDefinitionRegistry(@NotNull BeanDefinitionRegistry registry) throws BeansException {
// register some custom beans here using configProperties
  }

  @Override
  public void postProcessBeanFactory(@NotNull ConfigurableListableBeanFactory beanFactory) throws BeansException {
    // no post-process steps required
  }
}

ConfigProperties.java

@Data
@Configuration
@ConfigurationProperties("custom-props")
public class ConfigProperties {

  private String url;
  private String user;
  private String password;

}

application.yml

spring:
  config:
    import: "sm://"
  cloud:
    gcp:
      project-id: my-project
      secretmanager:
        enabled: true
        project-id: my-project

custom-props:
  url: myurl
  user: ${sm://user-key}
  password: ${sm://user-password}

If you look at application.yml I am trying to fetch secrets from gcp (it is able to get secrets) but since I implement EnvironmentAware (in PropertiesRegistrar) to bind my properties which is invoked very early in the startup, Binder is unable to convert secrets (user and password fields in properties) that are in com.google.protobuf.ByteString to String , due to which I am facing errors. I tried registering custom Converter<S, T> but they are of no use, since this binding happens too early during context buildup.

Now I want to know if there is a proper way to achieve this conversion (secrets conversion from ByteString to String ) at the time of above properties binding?

0

There are 0 answers