2

I’m developing an application in spring boot and deploying in PCF (Pivotal Cloud Foundry).

I’ve created 3 “user-provided” services and I would like to inject them in my code using @ConfigurationProperties into a class. I’ve been looking around but the only example I found is injecting a service into a class and I need to inject a list of services.

I’ve tried with @ConfigurationProperties(vcap.services) but it is not working. The class mapped is null. Can you please help me to understand how the CUPS can be injected in spring boot? Thanks in advance

Shiva
  • 6,677
  • 4
  • 36
  • 61
user3382975
  • 23
  • 1
  • 6

1 Answers1

2

When you create a user provided service in the following way

cf cups ups-example1 -p '{"user":"user1", "password":"password1"}'

and bind that to your application, the information provided in the user provided service gets mapped into your VCAP_SERVICES environment variable.

It should look something like

{
  "user-provided": [
   {
    "credentials": {
     "password": "password1",
     "user": "user1"
    },
    "label": "user-provided",
    "name": "ups-example1"
   }
  ]
}

With the help of Springs CloudFoundryVcapEnvironmentPostProcessor it gets mapped into an environment property which can be accessed by vcap.services.ups-example1.credentials.

To map these properties into a Java object you can use @ConfigurationProperties

@Configuration
@ConfigurationProperties("vcap.services.ups-example1.credentials")
public class UserProvidedServiceOneProperties {
  private String user;
  private String password;

  // getters & setters
}

If you want to map multiple user provided services into one object you could use inner classes for that use case

@Configuration
public class UserProvidedServicesProperties {

  @Autowired
  private UserProvidedServiceOneProperties userProvidedService1;

  @Autowired
  private UserProvidedServiceTwoProperties userProvidedService2;

  // getters & setters

  @Configuration
  @ConfigurationProperties("vcap.services.ups-example1.credentials")
  public static class UserProvidedServiceOneProperties {
    private String user;
    private String password;

    // getters & setters
  }

  @Configuration
  @ConfigurationProperties("vcap.services.ups-example2.credentials")
  public static class UserProvidedServiceTwoProperties {
    private String user;
    private String secret;
    private String url;

    // getters & setters
  }
}
benny.la
  • 1,212
  • 12
  • 26