应用程序主要用于JAX-RS web服务



我目前正在实现我的第一个基于JAX-RS的REST服务,在我研究JAX-RS期间,我发现了如何实现应用程序的主要"入口点"的两个版本。一种选择是实现一个在其主方法中启动服务器的类:

public class Spozz {
    public static void main(String[] args) throws Exception {
        //String webappDirLocation = "src/main/webapp/";
        int port = Integer.parseInt(System.getProperty("port", "8087"));
        Server server = new Server(port);
        ProtectionDomain domain = Spozz.class
                .getProtectionDomain();
        URL location = domain.getCodeSource().getLocation();
        WebAppContext webapp = new WebAppContext();
        webapp.setContextPath("/");
        webapp.setDescriptor(location.toExternalForm() + "/WEB-INF/web.xml");
        webapp.setResourceBase(location.toExternalForm());
        webapp.setServer(server);
        webapp.setWar(location.toExternalForm());
        webapp.setParentLoaderPriority(true);
        // (Optional) Set the directory the war will extract to.
        // If not set, java.io.tmpdir will be used, which can cause problems
        // if the temp directory gets cleaned periodically.
        // Your build scripts should remove this directory between deployments
        webapp.setTempDirectory(new File(location.toExternalForm()));
        server.setHandler(webapp);
        server.start();
        server.join();
    }
}

另一个扩展javax.ws.rs.core.Application类。

@ApplicationPath("/services")
public class Spozz extends Application {
    private Set<Object> singletons = new HashSet<Object>();
    private Set<Class<?>> empty = new HashSet<Class<?>>();
    public Spozz() {
        singletons.add(new UserResource());
    }
    @Override
    public Set<Class<?>> getClasses() {
        return empty;
    }
    @Override
    public Set<Object> getSingletons() {
        return singletons;
    }
}

然而,我在许多不同的例子中都见过这两个版本,但从来没有人解释为什么选择这个版本以及它的好处是什么。我个人会坚持第二个,但我真的没有理由。所以我的问题是:

  1. 这些选项有什么不同?
  2. 当使用JAX-RS 2.0时,哪一个更可取?
  3. 如果我想在服务中添加servlet,这很重要吗?

这些选项有什么不同?

选项#1实际上只是一个快速的开始。web容器有很多属性是你想在生产环境中调整的,比如线程池/线程数/连接器等。我不确定您的代码与哪个嵌入式容器相关,但web容器配置最好留给配置文件,而不是生产中的代码。

当使用JAX-RS 2.0时,哪一个更可取?

如果你正在制作原型,请使用第1条。对于生产使用#2。对于球衣应用程序的入口点,扩展Application类是可行的方法。所以这不是一个选择的问题。

如果我想在服务中添加servlet,这很重要吗?

我不知道那是什么意思。您想在以后添加servlet吗?无论您使用的是嵌入式容器还是独立容器,这都无关紧要。servlet就是servlet。

最新更新