【Spring Cloud】 【PropertySourceLocator】使用PropertySourceLocator来实现外部配置源

PropertySourceLocator 是 Spring Cloud 中的一个接口,用于在应用启动时,通过外部配置源(如 Nacos、Consul 等)加载配置并将其注入到 Spring 的 Environment 中。它允许开发者扩展 Spring 的配置加载机制,实现自定义的配置源。


接口定义

public interface PropertySourceLocator {
    PropertySource<?> locate(Environment environment);
}
  • locate(Environment environment): 返回一个 PropertySource 对象,表示从外部源加载的属性。可以根据当前的 Environment 环境(如 profiles)进行动态配置。

用法步骤

  1. 实现 PropertySourceLocator 接口

    • 创建一个自定义类,实现该接口,并在 locate 方法中定义如何加载外部配置。
  2. 将配置源注册到 Spring 上下文

    • 通过 Spring Boot 的自动配置机制,将自定义的 PropertySourceLocator 注册到应用中。

示例代码

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 自动注册方式

  1. spring.factories 文件
    如果需要通过自动配置加载:

    org.springframework.cloud.bootstrap.BootstrapConfiguration=\
    com.example.CustomDatabasePropertySourceLocator
    
  2. 配置文件生效
    放在 META-INF/spring.factories 下,Spring Boot 会在启动时自动加载。


常见场景

  • 从数据库读取配置
  • 与 Nacos、Consul 等配置中心集成
  • 从远程文件或 REST API 读取配置

这种机制使得应用可以在启动时灵活加载外部配置并动态更新。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值