用Jersey手动定义资源

时间:2012-08-19 13:05:50

标签: java jersey

我已将我的资源分配到界面 - impl因为它更有意义但是如果我让它扫描我的资源,这似乎不受最新版本的球衣的支持。

如何在web.xml中手动定义资源? 如果我在web.xml中手动定义资源impl,这会起作用吗?

感谢 亚历

1 个答案:

答案 0 :(得分:1)

[1]。创建一个扩展 javax.ws.rs.core.Application 的java类并注册您的资源:

public class MyRESTApp 
     extends Application {
    @Override
    public Set<Class<?>> getClasses() {
        Set<Class<?>> s = new HashSet<Class<?>>();

        s.add(MyResource.class);
        ....

        return s;
    }
}

[2]。在web.xml注册应用程序 如果您正在使用 spring ,请访问web.xml:

<servlet>
    <servlet-class>com.sun.jersey.spi.spring.container.servlet.SpringServlet</servlet-class>
    <init-param>
    <param-name>javax.ws.rs.Application</param-name>
        <param-value>com.xxx.MyRESTApp</param-value>
    </init-param>
    ...
</servlet>

如果你正在使用 guice ,请访问web.xml:

<filter>
    <filter-name>guiceFilter</filter-name>
    <filter-class>com.google.inject.servlet.GuiceFilter</filter-class>
</filter>

<filter-mapping>
   <filter-name>guiceFilter</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping>

<listener>
    <listener-class>com.xx.MyGuiceServletContextListener</listener-class>
</listener>

然后创建扩展 com.google.inject.servlet.GuiceServletContextListener

的java类MyGuiceServletContextListener
public class MyGuiceServletContextListener 
     extends GuiceServletContextListener {
    @Override
    protected Injector getInjector() {
        Guice.createInjector(new JerseyServletModule() {
@Override
protected void configureServlets() {
        // Route all requests through GuiceContainer
        // IMPORTANT
        // If this property is not defined guice tries to find the @Path annotated types defied at the injector
        Map<String,String> params = new HashMap<String, String>();
        params.put("javax.ws.rs.Application",
        MyRESTApp.class.getName());
        serve("/*").with(GuiceContainer.class,
                         params);
        });
    }
}