SpringCloud的自定义参数

送分小仙女□ 提交于 2020-02-15 12:54:05

基于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
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!