放置@EnableConfigurationProperties注释的最佳做法是什么



我有一个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)

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

这些注释有不同的用途。

CCD_ 1让开发人员可以很容易地将整个.properties.yml文件映射到一个对象中。

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

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

文件显示:

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

相关内容