基于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