我可以为 Spring 中的 @Component class 创建构造函数吗

Can I create a constructor for a @Component class in Spring

这是我的组件class

@Component
@ConfigurationProperties(prefix = "default-values")
public class DefaultConfig {

    private Map<String, String> countries = new HashMap<>();
    private WHO whoHdr;

    DefaultConfig() {

        countries.put("966 - Saudi Arabia", "966");
        countries.put("965 - Kuwait", "965");        
    }

}

在我的 application.yaml 文件下,我配置了要为 'WHO' 字段设置的值。

但是,既然我已经将DefaultConfig class定义为一个@Component,我可以单独创建一个构造函数来创建一个HashMap对象吗?因为如果我想将它注入另一个 class.

,我无法使用 New 关键字创建 DefaultConfig 的实例

有没有更好的方法让这个国家成为对象而不是将它们放在应该准备好自动装配的默认构造函数中?

@PostConstruct

是在 bean 注册到上下文之前执行的 bean 组件方法的注释。您可以在此方法中初始化默认值/常量值。

有关详细信息,请参阅下文 link:

https://www.journaldev.com/21206/spring-postconstruct-predestroy

首先:

您不需要将 @Component 放在标记为 @ConfigurationProperties 的 class 上,除了 spring 可以将配置数据映射到这些 classes,它们是常规的 spring bean,因此可以注入其他 classes。

但是您确实需要 "map" 此配置属性 @EnableConfigurationProperties(DefaultConfig.class) 在您的配置 class 之一上(甚至 @SpringBootApplication 这也是一个配置 class).

现在由于 @ConfigurationProperties 注释 class 是一个 spring bean,您可以在其上使用 @PostConstruct 来初始化地图:

@ConfigurationProperties(prefix = "default-values")
public class DefaultConfig {

    private Map<String, String> countries = new HashMap<>();
    private WHO whoHdr;

    @PostConstruct
    void init() {

        countries.put("966 - Saudi Arabia", "966");
        countries.put("965 - Kuwait", "965");        

    }  

    //setter/getter for WHO property 

}

@Configuration
@EnableConfigurationProperties(DefaultConfig.class)
class SomeConfiguration {

}

值得一提的是 Spring boot 2.2 ConfigurationProperties classes 可以是不可变的,所以你不需要 getter/setter.