@PropertySource
注解是 Spring 框架中的一个注解,用于指定一个或多个外部属性文件(如 .properties
文件),并将其加载到 Spring 的环境中。这个注解通常与 @Configuration
注解一起使用,以便在配置类中加载属性文件。
主要作用
-
加载外部配置:
@PropertySource
使得开发者可以将应用程序的配置(如数据库连接信息、API 密钥等)集中在一个或多个外部的属性文件中,而不是硬编码在 Java 代码中或直接放在配置类中。 -
提供访问属性的方式:加载的属性可以使用
@Value
注解进行访问,将属性值注入到 Spring Bean 中。 -
支持多个文件:可以使用多个
@PropertySource
注解或在一个注解中指定多个文件,以便加载多个属性文件。
语法
@PropertySource
的基本语法如下:
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
@Configuration
@PropertySource("classpath:application.properties") // 加载类路径下的属性文件
public class AppConfig {
// 配置 Bean
}
示例代码
以下是一个使用 @PropertySource
的简单示例:
1. 创建属性文件
首先,创建一个名为 application.properties
的文件,内容如下:
myapp.title=Hello, Spring
myapp.version=1.0.0
2. 创建 Spring 配置类
然后,在 Spring 配置类中使用 @PropertySource
注解加载这个属性文件:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
@Configuration
@PropertySource("classpath:application.properties") // 加载属性文件
public class AppConfig {
@Value("${myapp.title}") // 注入属性值
private String title;
@Value("${myapp.version}") // 注入属性值
private String version;
@Bean
public MyService myService() {
return new MyService(title, version); // 使用加载的属性值初始化 Bean
}
}
3. 创建服务类
定义一个 MyService
类,以使用加载的属性:
public class MyService {
private String title;
private String version;
public MyService(String title, String version) {
this.title = title;
this.version = version;
}
public void printInfo() {
System.out.println("App Title: " + title);
System.out.println("App Version: " + version);
}
}
4. 主程序
最后,创建主程序来运行 Spring 应用:
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
MyService myService = context.getBean(MyService.class);
myService.printInfo(); // 输出加载的属性值
}
}
执行结果
运行上述代码,输出将会是:
App Title: Hello, Spring
App Version: 1.0.0
总结
@PropertySource
注解的主要作用是加载外部属性文件,将其中的键值对加载到 Spring 的环境中。- 结合
@Value
注解,可以轻松地将配置中的属性值注入到 Spring Bean 中,增强了代码的灵活性和可维护性。 - 这种方式使得应用程序的配置可以更加集中和外部化,降低了对硬编码配置的依赖。