Spring @PropertySource 注解教程显示了如何使用@PropertySource 注解将属性包括到环境中以及如何使用@Value 注入属性。
Spring 是用于创建企业应用的流行 Java 应用框架。
Spring @PropertySource
@PropertySource
是方便的注释,用于将PropertySource
包含到 Spring 的环境中,并允许通过@Value
将属性注入类属性中。 (PropertySource
是代表来自特定来源的一组属性对的对象。)
@PropertySource
与@Configuration
一起使用。
Spring @PropertySource
示例
该应用使用 Spring 的@PropertySource
将application.properties
文件中的属性包含到环境中,并将它们注入类属性中。
这是项目结构。
pom.xml
在pom.xml
文件中,我们具有基本的 Spring 依赖项spring-core
,spring-context
和日志记录logback-classic
依赖项。
exec-maven-plugin
用于在命令行上从 Maven 执行 Spring 应用。
resources/logback.xml
logback.xml
是 Logback 日志库的配置文件。
resources/application.properties
application.properties
文件中有两个属性。
com/zetcode/config/AppConfig.java
AppConfig
是应用配置类。 @PropertySource
将属性从application.properties
注入到 Spring 的环境中。
com/zetcode/Application.java
在Application
中,我们使用两种方法获得属性。
我们注入Environment
。 我们可以使用getProperty()
方法检索属性。
我们将带有@Value
注解的属性注入到属性中。
检索属性的第一种方法是使用getProperty()
方法从Environment
。
第二种方法是使用注入的属性。
我们运行该应用。
在本教程中,我们展示了如何使用@PropertySource
注释在 Spring 应用中方便地使用属性。