使用Guice AOP在Jersey中拦截方法

时间:2012-06-11 14:56:12

标签: java jersey aop guice

是否可以使用Guice AOP拦截Jersey资源上的带注释的方法?

我有一个成功配置的Guice集成与Jersey一起使用依赖注入没有任何问题,但是我配置的拦截器根本没有拦截我的注释方法。

的web.xml

<listener>
    <listener-class>my.package.GuiceConfig</listener-class>
</listener>
<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>

GuiceConfig配置模块

public class GuiceConfig extends GuiceServletContextListener {

@Override
protected Injector getInjector() {
    return Guice.createInjector(new JerseyServletModule() {

            @Override
            protected void configureServlets() {

                bindInterceptor(Matchers.any(), 
                                Matchers.annotatedWith(RequiredAuthority.class), 
                                new AuthorisationInterceptor());

                Map<String, String> params = new HashMap<String, String>(); 
                params.put(JSP_TEMPLATES_BASE_PATH, "/WEB-INF/jsp"); 
                params.put(FEATURE_FILTER_FORWARD_ON_404, "true");
                params.put(PROPERTY_PACKAGES, "my.service.package");

                filter("/*").through(GuiceContainer.class, params);
            } 
        });
    }
}

RequiredAuthority注释

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface RequiredAuthority {
    String value();
}

AuthorisationInterceptor方面

public class AuthorisationInterceptor implements MethodInterceptor {

    public Object invoke(MethodInvocation methodInvocation) throws Throwable {

        // Allow invocation to process or throw an appropriate exception
    }
}

TempResource JAX-RS资源类

@Path("/temp")
public class TempResource {

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @RequiredAuthority("PERMISSION")
    public String getTemp() {

        // Return resource normally
    }
}

1 个答案:

答案 0 :(得分:5)

看起来configureServlets()没有调用:

bind(TempResource.class);