我可以在 Spring 中为 @Component 类创建构造函数吗

Sye*_*yed 6 java spring dependency-injection autowired

这是我的组件类

@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");        
    }

}
Run Code Online (Sandbox Code Playgroud)

在我的 application.yaml 文件下,我已经配置了为“WHO”字段设置的值。

但是,由于我已将 DefaultConfig 类定义为@Component,我可以单独创建一个构造函数来创建 HashMap 对象吗?因为如果我想将其注入到另一个类中,我无法使用 New 关键字创建 DefaultConfig 的实例。

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

Bri*_*att 11

@PostConstruct

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

请参阅以下链接了解更多信息:

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


Mar*_*nik 3

首先:

您不需要上@Component标记为的课程@ConfigurationPropertiesSpring 可以将配置数据映射到这些类的事实的类,它们是常规的 spring bean,因此可以注入到其他类中。

然而,您确实需要通过@EnableConfigurationProperties(DefaultConfig.class)您的配置类之一(甚至是@SpringBootApplication也是一个配置类)“映射”此配置属性。

现在由于@ConfigurationProperties带注释的类是一个 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 {

}
Run Code Online (Sandbox Code Playgroud)

值得一提的是,在 Spring boot 2.2 ConfigurationProperties 中,类可以是不可变的,因此您不需要 getter/setter。