PropertySourceLocator方式实现
PropertySourceLocator是spring cloud的接口用来完成自定义Bootstrap 配置
步骤:
- 继承PropertySourceLocator接口
public class CustomPropertySourceLocator implements PropertySourceLocator {
@Override
public PropertySource<?> locate(Environment environment) {
Map<String,Object> params = new HashMap<>();
params.put("kimName","kim");
params.put("kimPassword","123456");
MapPropertySource mapPropertySource = new MapPropertySource("kim",params);
return mapPropertySource;
}
}
- 在spring.factories中配置自定义配置类
org.springframework.cloud.bootstrap.BootstrapConfiguration=com.ruoyi.system.utils.CustomPropertySourceLocator
项目启动测试
public class SystemApplication
{
public static void main(String[] args) {
SpringApplication springApplication = new SpringApplication();
ConfigurableApplicationContext context = springApplication.run(RuoYiSystemApplication.class, args);
String kimName = context.getEnvironment().getProperty("kimName");
System.out.println("kimName=" + kimName);
}
}
项目启动可以输入kimName=kim
ApplicationContextInitializer方式实现
ApplicationContextInitializer 是Spring的标准接口用来完成自定义Bootstrap 配置
- 实现ApplicationContextInitializer
public class CustomApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
@Override
public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
MutablePropertySources propertySources = configurableApplicationContext.getEnvironment().getPropertySources();
Map<String,Object> params = new HashMap<>();
params.put("kimName","kim");
params.put("kimPassword","123456");
MapPropertySource mapPropertySource = new MapPropertySource("kim",params);
propertySources.addFirst(mapPropertySource);
}
}
- 加载CustomApplicationContextInitializer类
第一种方式:
public class SystemApplication
{
public static void main(String[] args)
{
SpringApplication springApplication = new SpringApplication(RuoYiSystemApplication.class);
springApplication.addInitializers(new CustomApplicationContextInitializer());
ConfigurableApplicationContext context = springApplication.run(args);
String kimName = context.getEnvironment().getProperty("kimName");
System.out.println("kimName="+kimName);
}
}
第二种方式也是在spring.factories中配置
org.springframework.cloud.bootstrap.BootstrapConfiguration=com.ruoyi.system.utils.CustomApplicationContextInitializer