2

我正在为 JAX-RS 使用 Spring 5.2.x 和 Jersey 2.30.x。

我有如下注释:

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyAnnotation {
}

在我的服务中,我使用以下注释:

@Service
public class MyService {
    @MyAnnotation
    public Response get() {
        ...
    }
}

@MyAnnotation当注释存在时,我想执行某些逻辑。为此,我创建了一个方面:

@Aspect
@Component
public class MyAspect {
    @Context
    private ContainerRequest request;

    @Pointcut("@annotation(so.MyAnnotation)")
    public void annotated() {
    }

    @Before("annotated()")
    public void test() {
        System.out.println("I need access to the HTTP headers: " + request);
    }
}

在这方面,我需要访问 HTTP 标头。我尝试注入 Jersey's ContainerRequest,但这似乎失败了:参考总是null.

所以我的问题是:如何ContainerRequest在 Spring 的托管 bean 中访问 Jersey 的上下文对象,例如 ?

最小的例子

我创建了一个最小的示例,请参阅https://github.com/pbillen/playground-so-61750237。您可以使用 构建它,mvn clean install -U然后使用mvn cargo:run. 如果您随后将浏览器指向http://localhost:8080/,您将在控制台中看到:

I need access to the HTTP headers: null

工作解决方案,绕过泽西岛并使用HttpServletRequest

我尝试HttpServletRequest在方面进行接线,然后访问Authorization标题:

@Aspect
@Component
public class MyAspect {
    @Autowired
    private HttpServletRequest request;

    @Pointcut("@annotation(so.MyAnnotation)")
    public void annotated() {
    }

    @Before("annotated()")
    public void test() {
        System.out.println(request.getHeader("authorization"));
    }
}

我还添加到web.xml

<listener>
    <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>

这基本上完全绕过了泽西岛。这似乎有效,我现在可以读出Authorization方面的标题。伟大的!

但是,我的问题仍然存在:有没有办法将 Jersey 的上下文对象注入 Spring 管理的方面?

4

0 回答 0