使用Guice进行构造函数注入 [英] Constructor Injection using Guice

查看:84
本文介绍了使用Guice进行构造函数注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些使用工厂的示例代码。我想通过删除工厂来清理代码,而改用Guice。我尝试这样做,但遇到了一个小障碍。我对Guice真的很陌生,所以我希望有人能在这里为我提供帮助。

I have some sample code which is using factories. I'd like to clean up the code by removing the factories and use Guice instead. I attempted to do this but I hit a small roadblock. I am really new to Guice, so I am hoping someone can help me out here.

现有客户代码(使用工厂):

Existing client code (Using factories):

public class MailClient {

    public static void main(String[] args) {
        MailConfig config = MailConfigFactory.get();
        config.setHost("smtp.gmail.com");
        Mail mail = MailFactory.get(config);
        mail.send();
    }
}

我尝试使用Guice进行重构:

My attempt to refactor using Guice:

//Replaces existing factories
public class MailModule extends AbstractModule {

    @Override
    protected void configure() {
        bind(Mail.class)
        .to(MailImpl.class);

        bind(MailConfig.class)
        .to(MailConfigImpl.class);
    }
}

public class MailImpl implements Mail {

    private final MailConfig config;

    @Inject
    public MailImpl(MailConfig config) {
        this.config = config;
    }

    public void send() { ... }
}

public class MailClient {

    public static void main(String[] args) {
        MailModule mailModule = new MailModule();
        Injector injector = Guice.createInjector(mailModule);
        MailConfig config = injector.getInstance(MailConfig.class);
        config.setHost("smtp.gmail.com");
        Mail mail = //??
        mail.send();
     }
}

如何构造<$ c $的实例c> MailImpl 在修订后的MailClient中使用对象 config ?我应该以这种方式使用Guice吗?

How would I construct an instance of MailImpl using the object config in my revised MailClient? Should I be using Guice in this way?

推荐答案

看看 AssistedInject 。看来可以解决这个问题。

Take a look at AssistedInject. It appears to address this problem.

这篇关于使用Guice进行构造函数注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆