简体   繁体   中英

Springboot - injection from application.yml depending method name

I refered Spring Boot - inject map from application.yml for injecting map from application.yml file

My application.yml snippet is below

easy.app.pairMap:
    test1: 'value1' 
    test2: 'value2'

Properties file is like below

@Component
@Configuration
@ConfigurationProperties("easy.app")
@EnableConfigurationProperties
public class TestProperties {



private Map<String, String> pairMap= new HashMap<String, String>();

public void setPairMap(Map<String, String> pairMap) {
    this.pairMap= pairMap;
}

}

But , I found that the value injection happens only when setters and getters are in proper format.ie getPairMap and setPairMap. Not when using getPairs or SetPairs. What is the reason for this behaviour

To bind to properties by using Spring Boot's Binder utilities (which is what @ConfigurationProperties does), you need to have a property in the target bean and you either need to provide a setter or initialize it with a mutable value.

How does Spring can understand that it needs to use SetPairs method to set your pairMap property? There is convention for naming of getters and setters and you should follow this convention if you want everything to work.

Spring takes your property full name easy.app.pairMap find ConfigurationProperties by prefix easy.app and then it try to find setter with name setPairMap , it takes property name pairMap and "converts" it to setPairMap .

If you create method setPairs property name should be like easy.app.pairs .

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