简体   繁体   English

如何根据环境在Java中加载资源文件?

[英]How to load resource files in java based on the environment?

So my team inherited a really large Java repository. 因此,我的团队继承了一个非常大的Java存储库。 It has a configuration file in the packed jar file. 它在打包的jar文件中有一个配置文件。

At several places in the code, it loads the configuration file as below: 在代码的多个位置,它加载配置文件,如下所示:

 InputStream in = classLoader.getResourceAsStream("configfile.config");

Now, based on the environment I want to be able to load a different config file. 现在,基于环境,我希望能够加载其他配置文件。 On dev, I want to be able to load configfile.dev.config and on prod I want to be able to load configfile.prod.config. 在dev上,我希望能够加载configfile.dev.config;在prod上,我希望能够加载configfile.prod.config。

What would be the most non-invasive, clean solution to this problem? 解决这个问题的最无创,最干净的方法是什么?

Is it a spring boot application? 它是Spring Boot应用程序吗? If yes, you can use different profiles like dev, testing and load the resource as per the profile.- https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-profiles.html 如果是,则可以使用不同的配置文件,例如dev,根据配置文件测试和加载资源。-https: //docs.spring.io/spring-boot/docs/current/reference/html/boot-features-profiles 。 html

If it's not spring boot application, then you can pass the profile value as JVM argument and use it in the code to load respective resouce. 如果不是Spring Boot应用程序,则可以将配置文件值作为JVM参数传递,并在代码中使用它来加载相应的资源。

  value=System.getProperty("profile");

Pass the profile value while running the application as - 在以以下方式运行应用程序时传递配置文件值:

  -Dprofile=test

You can use the passed profile and load respective file accordingly. 您可以使用传递的配置文件并相应地加载相应的文件。

  InputStream in = 
  classLoader.getResourceAsStream(value);

Since you don't seem to have framework support for this and are launching from the command line, the best approach is to use a system property. 由于您似乎对此没有框架支持,而是从命令行启动,因此最好的方法是使用系统属性。 There are two common approaches: 有两种常见方法:

  • Use a property such as config.location , where the value is a URI to the config file. 使用诸如config.location的属性,其中值是配置文件的URI。 This is more flexible and allows you to provide a new config file at runtime, but it makes it a bit more complicated to refer to one inside a jar (those URIs get long and need shell escaping). 这更加灵活,允许您在运行时提供一个新的配置文件,但是在jar中引用一个配置文件会更加复杂(这些URI会变长,并且需要转义shell)。

  • Use a property such as config.profile , where the value is a profile identifier such as dev or prod . 使用诸如config.profile的属性,其中值是诸如devprod类的配置文件标识符。 Name your included config files either /dev/config.file or /config-dev.file , and assemble the appropriate template name from the property. 将您包含的配置文件命名为/dev/config.file/config-dev.file ,然后从属性中组合适当的模板名称。

Based on your preference for including the multiple configurations inside the jar, the second option is probably a better fit. 根据您偏好在jar中包含多种配置,第二种选择可能更合适。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM