Dropwizard HK2注射

时间:2018-02-07 11:20:35

标签: java dependency-injection jersey dropwizard hk2

我在使用dropwizard时非常新。目前我正在尝试实现HK2依赖注入。这在资源内部工作得非常好,但它不能在资源之外工作。这就是我正在做的事情:

Client client = new JerseyClientBuilder(environment).using(configuration.getJerseyClientConfiguration()).build("contentmoduleservice");

    //DAOs
    ContentModuleDAO contentModuleDAO = new ContentModuleDAO(hibernate.getSessionFactory());
    ModuleServedDAO moduleServedDAO = new ModuleServedDAO(hibernate.getSessionFactory());

    //Manager
    ContentModuleManager moduleManager = new ContentModuleManager();
    EntityTagManager eTagManager = new EntityTagManager();
    ProposalManager proposalManager = new ProposalManager(client, configuration);

    environment.jersey().register(new AbstractBinder() {
        @Override
        protected void configure() {
            bind(eTagManager).to(EntityTagManager.class);
            bind(contentModuleDAO).to(ContentModuleDAO.class);
            bind(moduleServedDAO).to(ModuleServedDAO.class);
            bind(proposalManager).to(ProposalManager.class);
            bind(moduleManager).to(ContentModuleManager.class);
        }
    });

我创建了我想要注入的类的实例并绑定它们。

在我的资源中注入工作:

@Api
@Path("/api/contentmodule")
public class ContentModuleResource {

    static final Logger LOG = LoggerFactory.getLogger(ContentModuleResource.class);
    static final int MAX_PROPOSALS_PER_MODULE = 10;

    @Inject
    private ContentModuleDAO contentModuleDAO;

    @Inject
    private EntityTagManager eTagManager;

    @Inject
    private ProposalManager proposalManager;

    @Inject
    private ContentModuleManager contentModuleManager;

所有这些变量都填充了正确类的实例。

问题是:ContentModuleManager还应该通过注入来获取其中的一些类:

public class ContentModuleManager {

@Inject
private ContentModuleDAO contentModuleDAO;

@Inject
private ProposalManager proposalManager;

@Inject
private ModuleServedDAO moduleServedDAO;

但那些都是空的。有人可以解释一个dropwizard noob为什么会发生这种情况以及如何解决这个问题? :d

谢谢!

1 个答案:

答案 0 :(得分:4)

如果您要自己实例化该服务,那么它将不会经历DI生命周期并且永远不会被注入。如果您只是将服务注册为类

,则可以让容器创建服务
bind(ContentModuleManager.class)
    .to(ContentModuleManager.class)
    .in(Singleton.class);

另一方面,如果您自己创建所有服务并且所有服务都可用,那么为什么不根本不使用DI容器呢?只需通过构造函数传递所有服务。无论您是使用构造函数注入 1 还是手动传递构造函数,通过构造函数获取服务都是很好的做法,因为它允许更容易地测试服务。 / p>

1 - 构造函数注入

private Service service;

@Inject
public OtherService(Service service) {
   this.service = service;
}