ARTICLE DETAIL

资讯详情

深耕郑州网站建设与运营推广的一线实战洞察。

spring自定义加载属性文件-{续}(yml、yaml、properties)

spring自定义加载属性文件-{续}(yml、yaml、properties) spring自定义加载属性文件(yml、yaml、properties)上面的文章在容器初始化时不会对Conditional起作用所以要彻底重载属性文件要进行以下处理importorg.springframework.context.ApplicationContextInitializer;importorg.springframework.context.ConfigurableApplicationContext;importorg.springframework.core.env.ConfigurableEnvironment;importorg.springframework.core.env.PropertiesPropertySource;importorg.springframework.core.io.FileSystemResource;importorg.springframework.core.io.support.PropertiesLoaderUtils;importjava.io.IOException;importjava.util.Properties;/** * 提取公用的配置 */publicclassCommonPropertiesEnvironmentInitializerimplementsApplicationContextInitializerConfigurableApplicationContext{Overridepublicvoidinitialize(ConfigurableApplicationContextconfigurableApplicationContext){ConfigurableEnvironmentenvironmentconfigurableApplicationContext.getEnvironment();//这个位置写死FileSystemResourceresourcenewFileSystemResource(/home/wenlong/Desktop/config/common.properties);try{if(resource.exists()){PropertiespropertiesPropertiesLoaderUtils.loadProperties(resource);PropertiesPropertySourcepropertySourcenewPropertiesPropertySource(custom_common_properties,properties);//先放它项目内部的配置可以更新之environment.getPropertySources().addLast(propertySource);System.out.println(已完成自定义属性文件的读取);}else{System.out.println(不存在自定义属性文件);}}catch(IOExceptione){System.err.println(error when to load the common.properties, );e.printStackTrace();}}}在启动SpringBoot项目的主类中用以下方式启动publicstaticvoidmain(String[]args){/// 原启动方式// SpringApplication.run(MainStarter.class, args);SpringApplicationappnewSpringApplication(MainStarter.class);// 添加自定义初始化类app.addInitializers(newCommonPropertiesEnvironmentInitializer());app.run(args);}结束
返回列表