简体   繁体   English

Springboot-从application.yml注入取决于方法名称

[英]Springboot - injection from application.yml depending method name

I refered Spring Boot - inject map from application.yml for injecting map from application.yml file 我引用了Spring Boot- 从application.yml注入映射以从application.yml文件注入映射

My application.yml snippet is below 我的application.yml片段如下

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. 但是,我发现只有在setter和getter的格式正确时才会发生值注入。例如,getPairMap和setPairMap。 Not when using getPairs or SetPairs. 使用getPairs或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. 要使用Spring Boot的Binder实用程序( @ConfigurationProperties所做的)绑定到属性,您需要在目标Bean中具有一个属性,并且需要提供一个setter或使用一个可变值对其进行初始化。

How does Spring can understand that it needs to use SetPairs method to set your pairMap property? Spring如何才能理解需要使用SetPairs方法来设置pairMap属性? There is convention for naming of getters and setters and you should follow this convention if you want everything to work. 有一个用于命名getter和setter的约定,如果您希望一切正常,则应遵循此约定。

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 . 春天需要你的财产全名easy.app.pairMap找到ConfigurationProperties由前缀easy.app ,然后试图找到与名二传手setPairMap ,它需要属性名pairMap和“转换”它setPairMap

If you create method setPairs property name should be like easy.app.pairs . 如果创建方法setPairs属性名称应类似于easy.app.pairs

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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