Abhi
Abhi

Reputation: 330

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

Upvotes: 1

Views: 687

Answers (2)

Andrii Vdovychenko
Andrii Vdovychenko

Reputation: 300

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.

Upvotes: 2

Ulad
Ulad

Reputation: 1133

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.

Upvotes: 1

Related Questions