1

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

最初的想法是因为我创建CustomAuthenticator而不是让Guice创建它,因此它为null。我也尝试将CustomAuthenticator直接注入到安全模块 - customAuthenticator对象然后是null。不知道我做错了什么。

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 IMPL:

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(); 
    } 

} 

回答

1

你在你的代码的两个错误。

首先,您构建的任何东西新的将不会注入@Inject工作。 其次,你不能将东西注入模块。

为了解决这个问题,像这样重构你的代码。

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

谢谢。这有很大帮助。 – Raunak