ApplicationContextInitializer、PropertySourceLocator自定义bootstrap属性源

PropertySourceLocator方式实现

PropertySourceLocator是spring cloud的接口用来完成自定义Bootstrap 配置
步骤:

  1. 继承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;
   }
}
  1. 在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 配置

  1. 实现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);
    }
}
  1. 加载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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。