Seephor Seephor - 4 months ago 327
Java Question

Correct way to load values/properties from spring cloud consul

I have a spring boot application that has a lot of properties defined in a

.yml
file. I am moving away from having the properties in a file to having them in a cloud, so for this I am using the key/value feature in spring cloud consul.

I am able to retrieve a value for a given key from consul, but the only way I have seen documented and only way I have been able to do it is like so:

@Autowired
private Environment env;

@RequestMapping("/test")
String home() {
return env.getProperty("test.property");
}


This is fine and dandy, but I have some existing classes that are still set to load properties the old way:

@Value("${test.property}")
String testProperty;


After adding the dependency for spring cloud consul to my project, I get new errors saying that all these properties cannot be resolved. I assume it is because spring boot sees the consul dependency and is either ignoring the yml file or parts of it now.

Is there a way to get these properties to load from consul without having to change any code in the classes? Or will I need to change these classes to follow the example that uses the
env
object?

Also, any further insight into how spring cloud consul works with spring boot for this specific purpose would be greatly appreciated. There isn't a whole lot of documentation on it.

Answer

I was able to get this to work, but it was a little tricky. You need to have the spring cloud consul starter dependency added. I had just the spring cloud consul config dependency.

I had to add consul config properties to both my application.yml and bootstrap.yml, the properties in my boostrap just set the format and data-key:

spring:
  cloud:
    consul:
      config:
        format: YAML
        data-key: data

This tells spring boot to load a yaml blob that is the value of key data in my application config cloud directory.

The configuration in my application.yml is the default the provide in the example. Once I added those configs and the @autoconfiguration tag to my service main application class, everything started working.