根据我的研究和理解:
@ConfigurationProperties
从application.properties
中加载属性
您可以指定字段名称与application.properties
中属性的名称相对应
-- @ConfigurationProperties
不能与@Value
一起使用
@PropertySource
从指定的文件中加载属性
可以与@Value
或@Autowired Environment env;
一起使用
@Value
它与application.properties
一起使用
application.properties
默认加载(您不需要在@PropertySource
中指定)
参考资料
Spring Boot 配置属性示例:https://mkyong.com/spring-boot/spring-boot-configurationproperties-example/
Spring 属性源示例:https://mkyong.com/spring/spring-propertysources-example/
SpringApplication 将从以下位置加载 application.properties 文件并将其添加到 Spring 环境中:
https://docs.spring.io/spring-boot/docs/1.5.22.RELEASE/reference/html/boot-features-external-config.html
@ConfigurationProperties 注释。当放置在任何 Spring bean 上时,它指定该 bean 的属性可以从 Spring 环境中的属性中注入。
< Spring In Action >
您可以将配置文件捆绑在应用程序 jar 中,也可以将文件放在运行时环境的文件系统中,并在 Spring Boot 启动时加载它。
Spring Boot 会自动从项目类路径加载 application.properties 文件。
http://dolszewski.com/spring/spring-boot-application-properties-file/
4.1. application.properties:默认属性文件
Boot 将其典型的约定优于配置方法应用于属性文件。这意味着我们只需将 application.properties 文件放在 src/main/resources 目录中,它就会被自动检测到。然后,我们可以像平常一样注入任何已加载的属性。
因此,通过使用此默认文件,我们不必显式注册 PropertySource,甚至不必提供属性文件的路径。
https://www.baeldung.com/properties-with-spring
@ConfigurationProperties 指示 Spring 应根据名称将 java 字段绑定到某些匹配属性。
Spring 要求具有此注释的类必须是 Spring bean。
使用 @ConfigurationProperties 和 @Value 在 Spring 中注入值:
Spring Inject Values with @ConfigurationProperties and @Value