如何使用jax-rs的属性文件? [英] How do I use a properties file with jax-rs?

查看:233
本文介绍了如何使用jax-rs的属性文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始使用在Tomcat上运行的jax-rs来设置Web服务。有没有办法将属性文件与我的java项目(在eclipse中)捆绑在一起,以便我可以在运行时读取它的属性?另外,如果可能的话,放置它的最佳位置(通过网址无法看到),Web内容,WEB-INF等?

I've just been getting started setting up a web service with jax-rs running on Tomcat. Is there a way to bundle a properties file with my java project (in eclipse) so that I can read properties out of it at runtime? Also if it's possible, where would be the best location to put it (so that it couldn't be seen via a url), WebContent, WEB-INF, etc?

谢谢。

推荐答案

有几种选择:

选项1:你可以把它放在你的类路径下(在Eclipse中把它放在源文件夹下),这样你就可以通过类加载器访问它了: MyClass.class.getResourceAsStream(myproperties.properites)

Option 1: You can put it under your classpath (in Eclipse put it under and source folder), so you can access it via the Classloader: MyClass.class.getResourceAsStream("myproperties.properites")

注意MyClass也必须在同一个源文件夹中(实际上它有点复杂,它必须在同一个类加载器层次结构中,但是来自相同的文件夹将完成这项工作)

Pay attention that MyClass must also be in the same source folder (actually it's a bit more complex, it must be in the same classloader hierarchy, but any class from the same folder will do the job)

选项2:将它放在WEB-INF文件夹中。这是一个首选选项,因为您不需要处理类路径。你需要一个ServletContext来访问它: javax.servlet.ServletContext.getResourceAsStream(WEB-INF / myproperties.properites)

Option 2: Put it in WEB-INF folder. It's a preferred option, since you don't need to deal with the classpath. You'll need a ServletContext to access it: javax.servlet.ServletContext.getResourceAsStream("WEB-INF/myproperties.properites")

在jax-rs中,您可以在任何已注册的资源或提供者中使用@Context注释获取ServletContext。

In jax-rs you can obtain the ServletContext using the @Context annotation in any registered resource or provider.

这篇关于如何使用jax-rs的属性文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆