gpt4 book ai didi

java - 如何将 HttpServletRequest 注入(inject)非资源类?

转载 作者:行者123 更新时间:2023-11-30 10:44:33 28 4
gpt4 key购买 nike

我已经在我的资源类中使用 @Context 成功注入(inject)了 HttpServletRequest

是否可以将 HttpServletRequest 注入(inject)到非资源类中?我创建了一个类来执行各种网络操作,这些操作需要将值存储在 HttpSession 中。例如……

public class RequestExecutor {

@Context
HttpServletRequest request;

public Response performNetworkRequest(Request request) {

// Do network request - I want to access the session without passing the session object around my code everywhere.
return response;
}
}

这可能吗?

最佳答案

你不能使用@Context,见JSR-311对于 JAX-RS 1.1 和 JSR-339对于 JAX-RS 2.0:

JAX-RS provides facilities for obtaining and processing information about the application deployment context and the context of individual requests. Such information is available to Application subclasses (see section 2.1), root resource classes (see chapter 3), and providers (see chapter 4).

你也可以初始化子资源:

The ResourceContext interface provides access to instantiation and initialization of resource or subresource classes in the default per-request scope. It can be injected to help with creation and initialization, or just initialization, of instances created by an application.

另请参阅:ResourceContext#initResource

但是你可以使用继承:

public abstract class AbstractResource {

@Context
HttpServletRequest request;

protected Response performNetworkRequest() {
// do something with request
}
}

@Path("myResource")
public class MyResource extends AbstractResource {
// some methods
}

关于java - 如何将 HttpServletRequest 注入(inject)非资源类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37379215/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com