在 Spring 框架中,@PropertySource 表明是用于加载外部属性文件的主要工具。它许可开拓者将配置项集中到一个或多个属性文件中,从而使得运用程序的配置更加灵巧和可掩护。本文将详细先容 @PropertySource 表明的用法、特性及其运用示例。
1. 什么是 @PropertySource?@PropertySource 是 Spring 供应的一个表明,用于指示 Spring 容器加载特定的属性文件。通过将属性文件中的键值对注入到 Spring 的环境中,开拓者可以方便地管理运用程序的配置。
@PropertySource 表明常日用于配置类上,其语法如下:

@PropertySource("classpath:application.properties")
在这里,classpath: 表示属性文件位于类路径下。@PropertySource 也支持指定多个属性文件。
3. 示例代码3.1 创建属性文件首先,创建一个名为 application.properties 的文件,放在 src/main/resources 目录下,内容如下:
app.name=My Spring Application app.version=1.0.0
3.2 创建配置类
然后,创建一个配置类并利用 @PropertySource 表明加载属性文件:
import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.PropertySource;import org.springframework.beans.factory.annotation.Value;@Configuration@PropertySource("classpath:application.properties")public class AppConfig { @Value("${app.name}") private String appName; @Value("${app.version}") private String appVersion; @Bean public String applicationInfo() { return String.format("Application: %s, Version: %s", appName, appVersion); }}
在这个示例中,AppConfig 类通过 @PropertySource 表明加载 application.properties 文件,并利用 @Value 表明将属性注入到字段中。
3.3 利用属性接下来,创建一个 Spring Boot 运用来利用这些配置:
import org.springframework.boot.CommandLineRunner;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.context.ApplicationContext;import org.springframework.context.annotation.Bean;@SpringBootApplicationpublic class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } @Bean public CommandLineRunner commandLineRunner(ApplicationContext ctx) { return args -> { String appInfo = ctx.getBean("applicationInfo", String.class); System.out.println(appInfo); }; }}
在 DemoApplication 中,通过 CommandLineRunner 在运用启动时输出配置的运用信息。
4. 特性和把稳事变加载顺序:@PropertySource 加载的属性文件优先级较低。如果有多个属性文件,后加载的会覆盖前面加载的相同键。支持占位符:在属性文件中可以利用占位符(如 ${...})来引用其他属性。支持 YAML 文件:如果利用 Spring Boot,可以利用 @PropertySource 加载 .yaml 文件,但常日推举直策应用 Spring Boot 的 application.yml 文件。5. 小结@PropertySource 表明供应了一种大略而灵巧的办法来管理运用程序的外部配置。通过利用这个表明,开拓者可以将配置项集中到外部文件中,从而提高代码的可读性和可掩护性。
希望这篇博客能够帮助你深入理解 @PropertySource 表明的利用!
如有任何问题,欢迎谈论!