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();
}
}
謝謝。這有很大幫助。 – Raunak