When using ConfigurationProperties with a camelCase prefix, how do I solve "Prefix must be in canonical form"?

Viewed 9040

I had a property configured in my yml as

foobar:
  baz: 7

and a configuration class annotated with

@ConfigurationProperties(prefix = "foobar")

and everything was working fine.

The code in my organization is generally camelCase, so I renamed both the property and prefix to fooBar. IntelliJ is now highlighting the prefix = "foobar" line with the error, "Prefix must be in canonical form". What can I do, while keeping camelCasing in the yml config?

1 Answers

Spring Boot supports multiple formats of property names, but encourages you to access them in a canonical way.

Per Property Binding in Spring Boot 2.0:

It turns out the idea of relaxed property names is much easier to implement if you restrict it to one direction. You should always access properties in code using a canonical form, regardless of how they are represented in the underlying source.

The ConfigurationPropertyName class enforces these canonical naming rules, which basically boil down to “use lowercase kebab-case names”.

So, for example, you should refer to a property in code as person.first-name even if person.firstName or PERSON_FIRSTNAME is used in the underlying source.

You can keep your config yml in camel case:

fooBar:
  baz: 7

but change the access in the configuration class annotation to use kebab-case:

@ConfigurationProperties(prefix = "foo-bar")
Related