繁体   English   中英

动态每个REST(Jersey)请求绑定Guice中的配置

[英]Dynamic per REST(Jersey) request binding of configurations in Guice

我们在项目中使用Guice进行DI。 当前,我们具有一些配置(属性),这些属性在服务器启动时从文件加载。 然后将它们绑定到所有组件并用于所有请求。

但是现在,我们有多个属性文件并在启动时加载它们。 这些配置可能因每个REST(Jersey)请求而不同,因为它们取决于输入。

因此,我们需要为每个请求动态绑定这些配置。 我研究了@RequestScoped Guice API,但没有发现任何特别有用的东西。

几乎没有与此类似的问题,但是还没有运气。 你能帮我这个忙吗?

我提供2种方式来实现,这两种方式都在请求范围内。

  1. 对于可以在其中注入请求对象的类,请使用HttpServletRequest
  2. 使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM