如何将对象设置为上下文以便我可以使用@Context 在应用程序中的任何位置获取它

How to set an object to context so that i can get it anywhere in the application with @Context

我想将 MyObject class 实例设置为应用程序上下文,以便我可以在任何地方使用它:

@Context MyObject object

我使用了 Jedis,这让我可以通过上述方法访问 jedis

请帮助设置上下文。

我正在使用 dropwizard (jetty,jersery and jackson)

我有一些时间并写下了实现它的方法(仅球衣,没有使用其他 DI 框架)。

泽西岛符合 javax.inject 注释。您不使用上下文注释的原因是因为(听起来)您的 MyObject class 不是上下文对象(例如,它不会随着每个请求而改变,例如 HttpServletRequest 是可注入的)。所以我们需要绑定你的对象。

考虑我对 MyObject 的实现:

public class MyObject {

    String get() {
        return "I am an object"; 
    }
}

此对象需要在我的球衣 classes(资源、过滤器等)中可用。我使用这个 bean 写了一些资源:

@Path("context")
public class ContextResource {

    @Inject
    MyObject o;

    @GET
    public String get() {
        return o.get();
    }

}

请注意,我在这种情况下使用 javax.inject.Inject 注释来告诉 jersey 我想要注入这个特定的 bean。 我现在需要做的就是告诉泽西这个豆子。在我的 DW 应用程序中,我这样做:

public class Application extends io.dropwizard.Application<Configuration>{  

    @Override
    public void run(Configuration configuration, Environment environment) throws Exception {

        environment.jersey().register(ContextResource.class);
        environment.jersey().register(new AbstractBinder() {

            @Override
            protected void configure() {
                bind(MyObject.class).to(MyObject.class);
            }
        });
    }

    public static void main(String[] args) throws Exception {
        new Application().run("server", "/home/artur/dev/repo/sandbox/src/main/resources/config/test.yaml");
    }
}

请注意,我正在使用活页夹来绑定我的 bean。语法看起来很时髦,但本质上它是在做 "bind the type to the implementation"。因为我的类型是我的实现(我没有使用 MyObject 的接口),所以看起来像:

bind(MyObject.class).to(MyObject.class) 

现在 jersey 知道我的 bean 并且会很高兴地注入它。

运行 我所有的代码打印:

artur@pandaadb:~/dev/vpn$ curl localhost:9085/api/context
I am an object

希望这能带来一些关于如何在没有框架的情况下使用注入的见解。就我个人而言,我建议将 guice 与 dropwizard (google: dropwizard-guicey) 一起使用,这使得这些事情变得非常容易。

此致,

阿图尔