将服务对象注入 guice 模块

Injecting service object into guice module

我正在使用 PlayFramework (java) 和用于 DI 的 Guice,以及 pac4j。这是我的 Guice 模块基于 pac4j demo app 的样子。在代码中,我传递了一个 CustomAuthentication,我在其中注入了一个 SericeDAO 对象,但它始终为 null

最初的想法是因为我正在创建 CustomAuthenticator 而不是让 guice 创建它,因此它是空的。我还尝试将 CustomAuthenticator 直接注入安全模块 - customAuthenticator 对象当时为空。不确定我做错了什么。

public class SecurityModule extends AbstractModule {

    private final Environment environment;
    private final Configuration configuration;

    public SecurityModule(
            Environment environment,
            Configuration configuration) {
        this.environment = environment;
        this.configuration = configuration;
    }

    @Override
    protected void configure() {
        final String baseUrl = configuration.getString("baseUrl");

        // HTTP
        final FormClient formClient = new FormClient(baseUrl + "/loginForm", new CustomAuthenticator());

        final Clients clients = new Clients(baseUrl + "/callback", formClient);

        final Config config = new Config(clients);
        bind(Config.class).toInstance(config);

    }
}

CustomAuthenticator 实现:

public class CustomAuthenticator implements UsernamePasswordAuthenticator {

    @Inject
    private ServiceDAO dao;

    @Override
    public void validate(UsernamePasswordCredentials credentials) {
        Logger.info("got to custom validation");
        if(dao == null) {
            Logger.info("dao is null, fml"); // Why is this always null? :(
        }
    }
}

ServiceDAO 已经设置为 guice 模块

public class ServiceDAOModule extends AbstractModule {

    @Override
    protected void configure() {
        bind(ServiceDAO.class).asEagerSingleton();
    }

}

您的代码中有两个错误。

首先,您使用 new 构建的任何内容都不会使用 @Inject 进行注入。 其次,你不能将东西注入模块。

要解决此问题,请像这样重构您的代码。

  1. 确保 ServiceDaoModule 在其他模块之前加载。
  2. 重构安全模块如下:
    1. 删除所有构造函数参数/整个构造函数
    2. 将 CustomAuthenticator 绑定为急切的单例
    3. 创建并绑定提供者。在那里你可以@Inject 配置。
    4. 创建并绑定一个Provider,这个可以@Inject Configuration和一个FormClient
    5. 创建并绑定一个 Provider,其中 @Inject Clients。