根据args注入一个类

时间:2014-08-05 21:46:05

标签: java guice

我需要使用Guice构造一个ApplicationContext实例。我的大多数其他类都依赖于ApplicationContext。但是,ApplicationContext依赖于public static void main中可用的args数组。

目前,我必须手动创建ApplicationContext并调用setter,然后在请求Guice创建其他对象之前将其注入injectMembers。当Guice依赖于args时,是否有更好的方法来获取Guice创建的对象?

ApplicationContext appContext = new ApplicationContext();
// configure my appContext from command line args
injector.injectMembers(appContext);
MyAppFoo a = injector.getInstance(MyAppFoo.class);
a.doThings();

2 个答案:

答案 0 :(得分:2)

这是一种方法:

class ApplicationContext {
    @Inject @Named("args") String[] args;
}

class MyAppFoo {
    @Inject ApplicationContext context;
}

class ApplicationModule extends AbstractModule {
    private final String[] args;

    ApplicationModule(String[] args) {
        this.args = args;
    }

    @Override
    protected void configure() {
        bind(String[].class)
            .annotatedWith(Names.named("args"))
            .toInstance(args);

        bind(ApplicationContext.class);
        bind(MyAppFoo.class);
    }
}

public class Application {
    public static void main(String[] args) {
        Injector injector = Guice.createInjector(new ApplicationModule(args));
        MyAppFoo a = injector.getInstance(MyAppFoo.class);
        a.doThings();
    }
}

答案 1 :(得分:1)

您可以使用提供者或提供者方法构建ApplicationContext并在参与其他注入之前对其进行配置:

public static void main(String[] args) {

    Injector injector = Guice.createInjector(b -> {
        b.bind(ApplicationContext.class).toProvider(() -> {
            // construct and configure application context
            ApplicationContext ctx = new ApplicationContext();
            ctx.setSomething(args[0]);
            ctx.setSomethingElse(args[1]);
            return ctx;
        }).in(Singleton.class);
    });

}