英文:
spring boot - Can I read json files placed in src/main/resources by environment
问题
我有一个Spring Boot项目,其中的JSON文件根据环境放置在src/main/resources
目录下,就像这样:
src/main/resources/dataFiles/dev
- 包含开发环境的JSON文件
src/main/resources/dataFiles/local
- 包含本地环境的JSON文件,诸如此类。
我正在尝试根据活动环境读取JSON文件路径。
也就是模糊地说,类似于:
String path = "dataFiles/${spring.profiles.active}/someFile.json"
-
有没有办法使用Spring配置文件来实现这个?如何做?
-
如果我想以高效的方式来实现,应该怎么做?
谢谢
英文:
I have a spring boot project with json files placed by environment under src/main/resources
like this:
src/main/resources/dataFiles/dev
- contains dev json files
src/main/resources/dataFiles/local
- contains local json files, and so on.
I am trying to read the json file path depending on the active environment.
i.e. vaguely speaking, something like :
String path = "dataFiles/${spring.profiles.active}/someFile.json"
-
Is there a way to do this using spring profiles? How to ?
-
If I were to do this in an efficient way, what would it be ?
Thank you
答案1
得分: 0
可以的,你可以这样做。在你进行读取的组件中,注入Environment
:
@Autowired
private Environment environment;
然后获取激活的配置文件:
String[] activeProfiles = environment.getActiveProfiles();
请注意,可能有多个配置文件处于激活状态,因此这会返回一个数组。如果你确定只会设置一个激活配置文件,那么可以这样获取文件路径:
String path = "dataFiles/" + activeProfiles[0] + "/someFile.json";
可能更好的方法是为每个配置文件创建一个属性文件,并在配置文件中放置数据路径。例如,对于本地配置文件,创建一个名为application-local.yml
的文件,然后在其中添加一个名为datapath
的属性,设置为"datafiles/local/"
。在读取文件的组件中,你只需注入这个属性:
@Value("${datapath}")
String dataPath;
然后可以像这样读取文件:
String path = dataPath + "someFile.json";
英文:
In short, yes you can do this. In your component that you are doing the read, inject Environment
@Autowired
private Environment environment;
Then get the profiles with
String [] activeProfiles = environment.getActiveProfiles();
Keep in mind that many profiles may be active, so this returns an array. If you are certain that you will only set a single active profile, then you can the get the file as
String path = "dataFiles/" + activeProfiles[0] + "/someFile.json";
Probably a better approach would be to create property file for each of your profiles ad place the data path in the profile. e.g. for the local profile, create a application-local.yml file, and put a property in there called something like datapath, set to "datafiles/local/"
. In your component that reads the file, then you just have to inject this property
@Value("${datapath}")
String dataPath;
The read your file like
String path = dataPath + "someFile.json";
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论