springboot 加载外部配置文件
开发springboot应用时经常有多个配置文件,开发的,测试的,生产环境的。 而生产环境的敏感数据又不希望泄露出去,所有想看看springboot有没有办法加载外部文件的办法。
因为springboot 默认加载配置文件的位置是
classpath:/,classpath:/config/,file:./,file:./config/
打包jar运行也不方便修改jar内部数据,一开始准备自己写个加载方法,后来看到spring的加载器配置文件ConfigFileApplicationListener里面有加载文件的功能,刚好不用自己写了。
spring定义的外部文件名称参数
public static final String CONFIG_ADDITIONAL_LOCATION_PROPERTY = "spring.config.additional-location";
在这里有使用
private Set<String> getSearchLocations() { if (this.environment.containsProperty(CONFIG_LOCATION_PROPERTY)) { return getSearchLocations(CONFIG_LOCATION_PROPERTY); } Set<String> locations = getSearchLocations( CONFIG_ADDITIONAL_LOCATION_PROPERTY); locations.addAll( asResolvedSet(ConfigFileApplicationListener.this.searchLocations, DEFAULT_SEARCH_LOCATIONS)); return locations; } private Set<String> getSearchLocations(String propertyName) { Set<String> locations = new LinkedHashSet<>(); if (this.environment.containsProperty(propertyName)) { for (String path : asResolvedSet( this.environment.getProperty(propertyName), null)) { if (!path.contains("$")) { path = StringUtils.cleanPath(path); if (!ResourceUtils.isUrl(path)) { path = ResourceUtils.FILE_URL_PREFIX + path; } } locations.add(path); } } return locations; }
然后断点调试了下,发现数据是从系统变量里面取的,所以使用方式就是设置spring.config.additional-location到系统变量中,多个可以用逗号隔开。
如
java -jar -Dspring.config.additional-location=/home/application-xxx.properties xxx.jar
需要注册该文件是最先加载,也就是里面的数据会被其他文件的覆盖
第二个办法是设置环境变量spring.config.location,因为前面加载逻辑是先判断该变量有没有设置,然后再加载默认的
spring.config.location=classpath:/,classpath:/config/,file:./,file:./config/,/自定义文件或目录
这样就可以灵活控制加载的先后顺序了 后面的会覆盖前面的

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。
持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。
转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。
- 上一篇
TP5的字符串截取超过字符...显示
在公共的common.php中 function subtext($text, $length) { if(mb_strlen($text, ‘utf8’) > $length) return mb_substr($text,0,$length,’utf8′).’ …’; return $text; } 在模版中调用则: {$tops.title | subtext=18}
- 下一篇
JakartaEE Exception: Invalid bound statement (not found): com.mazaitin...
异常 org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.mazaiting.blog.dao.UserDao.selectUserByName at org.apache.ibatis.binding.MapperMethod$SqlCommand.<init>(MapperMethod.java:227) ~[mybatis-3.4.6.jar:3.4.6] at org.apache.ibatis.binding.MapperMethod.<init>(MapperMethod.java:49) ~[mybatis-3.4.6.jar:3.4.6] at org.apache.ibatis.binding.MapperProxy.cachedMapperMethod(MapperProxy.java:65) ~[mybatis-3.4.6.jar:3.4.6] at org.apache.ibatis.binding.MapperProxy...
相关文章
文章评论
共有0条评论来说两句吧...
文章二维码
点击排行
推荐阅读
最新文章
- SpringBoot2编写第一个Controller,响应你的http请求并返回结果
- CentOS8编译安装MySQL8.0.19
- Hadoop3单机部署,实现最简伪集群
- SpringBoot2整合Redis,开启缓存,提高访问速度
- SpringBoot2初体验,简单认识spring boot2并且搭建基础工程
- Eclipse初始化配置,告别卡顿、闪退、编译时间过长
- CentOS7安装Docker,走上虚拟化容器引擎之路
- SpringBoot2整合Thymeleaf,官方推荐html解决方案
- SpringBoot2配置默认Tomcat设置,开启更多高级功能
- Springboot2将连接池hikari替换为druid,体验最强大的数据库连接池