Constructor Injection using Guice

此生再无相见时 提交于 2019-12-05 06:10:25
Jesse Wilson

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

Andreas Petersson

2 solutions are possible: 1) bind the config as a guice object also, including its host parameter. then just inject Mail, in your main method you cna ignore the fact that mail has further dependencies.

2) mail must be configured individually for each send (recipient?). then you have no choice, but create it yourself using MailFactory.

You can do everything in MailModule as follows:

public class MailModule extends AbstractModule {
    @Override
    protected void configure() {
       ... // other bindings
    }

    @Provides
    MailConfig getMailConfig( ... ) {
        MailConfig config = new MailConfig( ... );
        config.setHost("smtp.gmail.com");
        config;
    }
}

If you want a singleton MailConfig, add the @Singleton annotation to getMailConfig(), and Bob's your uncle.

Note that arguments to getMailConfig must be bound. When you bind commonly used types like String, be sure to add a binding annotation.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!