【问题标题】:What is the best practice for placing an @EnableConfigurationProperties annotation? [closed]放置 @EnableConfigurationProperties 注释的最佳做法是什么? [关闭]
【发布时间】:2020-09-02 12:20:19
【问题描述】:

我有一个 SpringBoot 应用程序,有一些附加的属性类用 @ConfigurationProperties 注释,而且,我还有一些配置。使用 @Configuration 注释的类。

放置 @EnableConfigurationProperties 注释的最佳位置是什么?我在主类上方看到它,但在配置上方。作为属性类的消费者的类,似乎是更好的放置位置,对我来说更有意义。放置此注释的最佳做法是什么?

例如:

@SpringBootApplication
//should it be here:
//@EnableConfigurationProperties(MyConfigProperties::class)
class MyApplication

fun main(args: Array<String>) {
  runApplication<MyApplication>(*args)
}

    

@Configuration
//or here?
//@EnableConfigurationProperties(MyConfigProperties::class)
class MyConfig(
    private val props: MyConfigProperties
){

    // some methods, that uses props
}



@ConstructorBinding
@ConfigurationProperties("props")
data class MyConfigProperties(val myProp: String)

【问题讨论】:

    标签: java spring spring-boot kotlin


    【解决方案1】:

    根据我的经验,您应该将注释放在使用这些属性的配置类中。

    【讨论】:

    • 谢谢,您这样做有什么原因吗,还是因为它通常放在那里?
    • 因为在配置类中,您还声明了可能使用这些属性或与某个包相关的 bean,例如,如果您使用的是 DDD。此外,主类应使用具有全局目的的注释保持清洁。
    【解决方案2】:

    这些注释有不同的用途。

    @ConfigurationProperties 让开发人员可以轻松地将整个.properties.yml 文件映射到一个对象中。

    @Configuration 表示该类可以被 Spring IoC 容器用作 bean 定义的来源。

    @ConfigurationProperties的一大优势可以是Externalized Configuration

    文档说:

    Spring Boot 允许您将配置外部化,以便您可以 在不同的环境中使用相同的应用程序代码。你可以 使用属性文件、YAML 文件、环境变量和 用于外部化配置的命令行参数。属性值 可以通过使用 @Value 直接注入到你的 bean 中 注解,通过 Spring 的 Environment 抽象访问,或者 通过@ConfigurationProperties 绑定到结构化对象。

    【讨论】:

    • 谢谢,但这不是我的问题的答案。我的问题是,哪个类应该用@EnableConfigurationProperties(MyProps)注解。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-01
    • 2019-01-12
    • 1970-01-01
    • 2010-09-29
    • 2012-08-07
    • 2011-06-30
    相关资源
    最近更新 更多