如何从 Spring 应用程序内部加载此文件路径
我之前对加载 json 文件的路径进行了硬编码,如下所示:
JsonParser parser = jf.createJsonParser(new File("/some/path/here/myapp/WEB-INF/settings.json"));
因此,我尝试将其提取到属性文件中,如下所示,files.properties:
path.to.json=/some/path/here/myapp/WEB-INF/settings.json
现在如何修改对 jf.createJsonParser
使用 files.properties path.to/json
键中的路径加载文件?
I was previously hard coding a path to load a json file like so:
JsonParser parser = jf.createJsonParser(new File("/some/path/here/myapp/WEB-INF/settings.json"));
So I tried to extract it out to a properties file like so, files.properties:
path.to.json=/some/path/here/myapp/WEB-INF/settings.json
Now how can I modify my call to jf.createJsonParser
to load the file using the path from the files.properties path.to/json
key?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我有点困惑。你的标题表明你正在寻找一个 Spring 解决方案,但据我所知,你在这里没有使用 IOC。否则,您将注入 JsonParser bean,而不是在代码中实例化它。
在没有看到你正在做的事情的全局结构的情况下,我会执行以下操作(假设你已经正确配置了 Spring)。
applicationContext.xml:
然后在使用 JsonParser 的实际类中,为了简单起见,将其自动装配:
我假设 JsonParser 属于原型范围,但如果更适合您的需求,您可以将其更改为单例。另外,我只给了您一些伪代码,让您了解如何让 Spring 管理 bean 的生命周期,而不是您自己实例化它。
您可以阅读有关 Spring 3 和 IOC 的更多信息 如果您需要其他参考,请点击此处。
I'm a little confused. Your title indicates that you are looking for a Spring solution, but you are not using IOC here, from what I can tell. Otherwise, you would be injecting the
JsonParser
bean and not instantiating it within your code.Without seeing the global structure of what you are doing, I would do the following (assuming that you have Spring properly configured).
applicationContext.xml:
Then within your actual class that uses the JsonParser, have it autowired for simplicity sake:
I've assumed that JsonParser is of scope prototype, but you can change it to singleton if that matches your needs more appropriately. As well, I've only given you a little pseudo-code to give you the idea of how to allow Spring to manage the life-cycle of the bean as opposed to you instantiating it yourself.
You can read more about Spring 3 and IOC here if you need additional reference.
如果您可以将文件放入源文件夹中,请尝试
"classpath:/"
示例:
If you can put your file into a source folder, do it and try
"classpath:/"
Example:
我不知道您是否正在寻找 Spring 特定的解决方案,但我认为使用 JCL 没有任何问题。
I don't know whether your looking for a Spring specific solution, but I see nothing wrong with using the JCL.