我构建了一个简单的 Jersey Rest 服务器,用于处理简单的服务。 在启动服务器的主类中,我读取了我想要的属性文件 提供/传递给 Jax 处理程序类。 服务器工作正常,我只需要找到一种方法来共享配置参数 带有请求处理程序的主类。 我怎样才能做到这一点?
<小时/>main 的代码,我只在其中读取一次属性文件:
...
public HashMap resources;
// this start the listener jersey server...
String host="http://localhost/";
int port = 9998;
URI baseUri = UriBuilder.fromUri(host).port(port).build();
ResourceConfig config = new ResourceConfig();
config.packages(true, "br.com.myserver");
config.register(MyHandler.class);
// I WANT TO ACCESS/SHARE THIS WITH THE HANDLER -> MyHandler.class
resources.put("host_user","bla bla bla");
HttpServer server = JdkHttpServerFactory.createHttpServer(baseUri, config);
System.out.println("--Press Enter to STOP the server--");
System.in.read();
Server.stop(0);
System.out.println("Server stoped!");
...
<小时/>
MyHandler 的代码,我想在其中访问主要属性:
@Path("myapp")
public class MyHandler
{
@POST @Path("/testep")
@Consumes("application/json")
@Produces("text/plain")
public String action1(@Context Request request, String json)
{
// HERE I WANT TO ACCESS THE RESOUCES HASHMAP OF MAIN HERE
// (how get main handler here).resources.get("host_user");
// maybe access main class, or something like
// the intention is to avoid the read of config at all requests here
System.out.println("received event:" + json);
return "event received " + json;
}
}
任何想法都会受到赞赏,谢谢。
最佳答案
您使用 property(key, value)
配置 ResourceConfig
的任何属性都可以通过 Configuration
访问您可以将其注入(inject)到资源类中的接口(interface)。
ResourceConfig config = new ResourceConfig();
config.property("host_user","bla bla bla");
...
@Path("myapp")
public class MyHandler
{
@Context
Configuration configuration;
public String action1(@Context Request request, String json) {
Map<String, Object> props = configuration.getProperties();
}
}
另请参阅:
关于java - Jersey JAX-RS 独立服务器 - 如何将参数传递给请求处理程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34858141/