PropertySourceLocator
是 Spring Cloud 中的一个接口,用于在应用启动时,通过外部配置源(如 Nacos、Consul 等)加载配置并将其注入到 Spring 的 Environment
中。它允许开发者扩展 Spring 的配置加载机制,实现自定义的配置源。
接口定义
public interface PropertySourceLocator {
PropertySource<?> locate(Environment environment);
}
locate(Environment environment)
: 返回一个PropertySource
对象,表示从外部源加载的属性。可以根据当前的Environment
环境(如 profiles)进行动态配置。
用法步骤
-
实现
PropertySourceLocator
接口:- 创建一个自定义类,实现该接口,并在
locate
方法中定义如何加载外部配置。
- 创建一个自定义类,实现该接口,并在
-
将配置源注册到 Spring 上下文:
- 通过 Spring Boot 的自动配置机制,将自定义的
PropertySourceLocator
注册到应用中。
- 通过 Spring Boot 的自动配置机制,将自定义的
示例代码
1. 自定义配置源(从数据库读取配置)
import org.springframework.core.env.Environment;
import org.springframework.core.env.PropertySource;
import org.springframework.core.env.MapPropertySource;
import org.springframework.cloud.bootstrap.config.PropertySourceLocator;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
@Component
public class CustomDatabasePropertySourceLocator implements PropertySourceLocator {
@Override
public PropertySource<?> locate(Environment environment) {
// 模拟从数据库获取配置
Map<String, Object> customConfig = new HashMap<>();
customConfig.put("custom.config.enabled", true);
customConfig.put("custom.config.name", "DatabaseConfig");
return new MapPropertySource("customDatabaseSource", customConfig);
}
}
2. 配置生效
- Spring Cloud 会在启动时自动调用
PropertySourceLocator
,将返回的PropertySource
注入到Environment
。
动态刷新示例
配合 Spring Cloud 的动态刷新机制,可以使用 @RefreshScope
自动刷新属性:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
@RefreshScope
@Service
public class CustomConfigService {
@Value("${custom.config.name:DefaultName}")
private String configName;
public String getConfigName() {
return configName;
}
}
Spring Boot 自动注册方式
-
spring.factories
文件:
如果需要通过自动配置加载:org.springframework.cloud.bootstrap.BootstrapConfiguration=\ com.example.CustomDatabasePropertySourceLocator
-
配置文件生效:
放在META-INF/spring.factories
下,Spring Boot 会在启动时自动加载。
常见场景
- 从数据库读取配置。
- 与 Nacos、Consul 等配置中心集成。
- 从远程文件或 REST API 读取配置。
这种机制使得应用可以在启动时灵活加载外部配置并动态更新。