简体   繁体   中英

Is there a replacement of PropertySourcesBinder in Spring Boot 2.X.X?

In Spring Boot 1.XX there was a class named PropertySourcesBinder.class. Please check the API link. PropertySourcesBinder.class

The purpose of the class is simple - receiving a org.springframework.core.env.ConfigurableEnvironment environment in the constructor, it was easy to use the extractAll (String somePrefixHere) properties starting with the given prefix. However seems like in Spring Boot 2.XX this class is missing.

This very method however was very useful since creating Map<String subKey, Map<String, Map>> with the properties recursively that match the prefix, same way omitting the prefix itself, which is very useful when having Spring "deep" properties like ABC.DEFGHI.... and you do not know how deep exactly it will go.

I am afraid my question is not very clear, however believe people have been using this class will understand what exactly my problem is?

It sounds like you should use the new Binder API:

ConfigurableEnvironment environment = new StandardEnvironment();
Map<String, Object> source = new HashMap<>();
source.put("your.prefix.a.b.c.e.f", "one");
source.put("your.prefix.a.b.c.e.g", "two");
source.put("your.prefix.a.b.c.e.h.i.j.k", "three");
environment.getPropertySources().addFirst(new MapPropertySource("example", source));

Bindable<Map<String, Map>> bindable = Bindable.mapOf(String.class, Map.class);
Map<String, Map> bound = Binder.get(environment).bind("your.prefix", bindable).get();
System.out.println(bound);

The above will output the following:

{a={b={c={e={f=one, g=two, h={i={j={k=three}}}}}}}}

Are you looking for this?

@ConfigurationProperties(prefix = “myprops”)

Here is an example:

Baeldung example for ConfigurationProperties

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM