【问题标题】:Can I create a constructor for a @Component class in Spring我可以在 Spring 中为 @Component 类创建构造函数吗
【发布时间】:2019-12-12 09:32:54
【问题描述】:

这是我的组件类

@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 类定义为 @Component,我可以单独创建一个构造函数来创建一个 HashMap 对象吗?因为如果我想将它注入到另一个类中,我无法使用 New 关键字创建 DefaultConfig 的实例。

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

【问题讨论】:

    标签: java spring dependency-injection autowired


    【解决方案1】:

    @PostConstruct

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

    更多信息请参考以下链接:

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

    【讨论】:

    • before the bean is ready for injecting to your application 您可能希望将其改写为在将 bean 注册到上下文之前,因为没有经验的用户可能会将其理解为在 DI 之前调用它已应用于 bean(事实并非如此)。
    【解决方案2】:

    首先:

    您不需要将@Component 放在标记为@ConfigurationProperties 的类上,因为spring 可以将配置数据映射到这些类中,它们是常规的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 {
    
    }
    

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

    【讨论】:

    • 谢谢马克。无论如何,将一个类注入非spring bean类
    • 一般情况下不会,因为它的弹簧只有在管理它们的情况下才能将 A 注入到 B 类中。可能有一些变通方法取决于您的具体情况,但无论如何请考虑提出另一个问题
    猜你喜欢
    • 2017-11-13
    • 1970-01-01
    • 2012-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-30
    • 2018-07-18
    相关资源
    最近更新 更多