[英]Dynamic per REST(Jersey) request binding of configurations in Guice
我们在项目中使用Guice进行DI。 当前,我们具有一些配置(属性),这些属性在服务器启动时从文件加载。 然后将它们绑定到所有组件并用于所有请求。
但是现在,我们有多个属性文件并在启动时加载它们。 这些配置可能因每个REST(Jersey)请求而不同,因为它们取决于输入。
因此,我们需要为每个请求动态绑定这些配置。 我研究了@RequestScoped
Guice API,但没有发现任何特别有用的东西。
几乎没有与此类似的问题,但是还没有运气。 你能帮我这个忙吗?
我提供2种方式来实现,这两种方式都在请求范围内。
HttpServletRequest
。 ThreadLocal
通用方法。 它可以在任何类中使用。 我的意思是这样的:
public class RequestFilter implements ContainerRequestFilter {
@Context
private HttpServletRequest request;
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
List listOfConfig = //load Config;
request.setAttribute("LOADED_CONFIG",listOfConfig);
// If you want to access this value at some place where Request object cannot be injected (like in service layers, etc.) Then use below ThreadLocals.
ThreadLocalWrapper.getInstance().get().add("adbc"); // In general add your config here, instead of abdc.
}
}
我的ThreadLocalWrapper看起来像这样:
public class ThreadLocalWrapper {
private static ThreadLocal<List<String>> listOfStringLocals; // You can modify this to a list of Object or an Object by itself.
public static synchronized ThreadLocal<List<String>> getInstance() {
if (listOfStringLocals == null) {
listOfStringLocals = new ThreadLocal<List<String>>() {
@Override
protected List<String> initialValue() {
return new ArrayList<String>();
}
};
}
return listOfStringLocals;
}
}
要访问值:
在Controller中 -注入HttpServletRequest
对象并执行getAttribute()以获取值。 由于HttpServletRequest
对象是requestScoped,因此可以设置加载的配置。 并在您控制器的使用request Object中再次访问它。
在代码的任何其他部分中 -如果HttpServletRequest
不可用,那么您始终可以使用所示的ThreadLocal示例。 要访问此值。
public class GuiceTransactionImpl implements GuiceTransaction {
private String value = "";
public GuiceTransactionImpl(String text) {
value = text;
}
@Override
public String returnSuccess() {
return value + " Thread Local Value " + ThreadLocalWrapper.getInstance().get();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.