将变量传递给Jersey中的资源类

时间:2016-02-24 16:36:18

标签: java resources jersey

我试图使用通过命令行参数传递给main函数的变量,并且应该在泽西的资源类中以某种方式可见。

我的主要职能:

public class MyApp extends ResourceConfig {

    public MyApp(String directory) {

        // I would like the MyResource.class to have access to the 
        // variable that is passed in the main function below, 
        // which is the directory variable
        register(MyResurce.class);
    }

    public void startHttpServer(int port) { ... }

    // args[0]: a port to start a HTTP server
    // args[1]: a string that is CONSTANT and UNIQUE throughout the 
    // full execution of the app, and the MyResource.class resource        
    // should be able to read it. How can I pass this variable to the resource?
    public static void main(String[] args)  {
            final MyApp app = new MyApp(args[1]);
            int port = Integer.parseInt(args[0]);
            app.startHttpServer(port);
    }
}

资源类没有什么特别之处,只有@ GET,@ DELETE和@POST方法。我应该怎么做才能使args [1]中给出的变量不仅可以看到MyResource.class,而且可以看到注册的所有资源?

1 个答案:

答案 0 :(得分:2)

如果您在资源类中注入JAX-RS应用程序,则可以访问属性Map

@Path(...)
public class MyResource {

    @Context
    private Application app;

    @GET
    @Path(...)
    public String someMethod() {
        String directory = app.getProperties().get("directory");
        ...
    }
}

然后,你的主要课程将是这样的:

public class MyApp extends ResourceConfig {

    public MyApp(String directory) {
        register(MyResource.class);

        Map<String, Object> properties = new HashMap<>();
        properties.put("directory", directory);
        setProperties(properties);
    }

    public void startHttpServer(int port) { ... }

    public static void main(String[] args)  {
        final MyApp app = new MyApp(args[1]);
        int port = Integer.parseInt(args[0]);
        app.startHttpServer(port);
    }
}

ResourceConfig扩展Application以来,您可以执行上述操作。