SpringCloud的自定义参数

基于SpringCloud开发框架时,有时候需要添加一些默认参数。
有2种方式可以实现。

  • PropertySourceLocator接口。
import org.springframework.cloud.bootstrap.config.PropertySourceLocator;
public class MyPropertySourceLocator implements PropertySourceLocator {
    @Override
    public PropertySource<?> locate(Environment environment) {
        Map<String, Object> properties = new HashMap<>();

        properties.put("waitTime", "1h");
        properties.put("seconds", "5s");
        
        PropertySource source = new MapPropertySource("MyProperty", properties);

        return source;
    }
}

需要有configuration类

@Configuration
public class MyAutoConfiguration {

    @Bean
    public MyPropertySourceLocator myPropertySourceLocator(){
        return new MyPropertySourceLocator();
    }
}

同时需要添加到spring.factories

org.springframework.cloud.bootstrap.BootstrapConfiguration=\
com.aaa.configuration.MyAutoConfiguration
  • EnvironmentPostProcessor接口。
import org.springframework.boot.env.EnvironmentPostProcessor;
public class MyEnvironmentPostProcessor implements EnvironmentPostProcessor {

    public PropertySource<?> getPropertySource() {
        Map<String, Object> properties = new HashMap<>();

        properties.put("aaa", "1h");
        properties.put("bbb", "5s");
        
        PropertySource source = new MapPropertySource("MyProperty", properties);

        return source;
    }

    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        //addFirst会具有最高优先级,addLast会具有最低优先级。
        environment.getPropertySources().addFirst(getPropertySource());
    }
}

同样需要加入到spring.factories文件里。

org.springframework.boot.env.EnvironmentPostProcessor=\
com.aaa.configuration.MyEnvironmentPostProcessor
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值