Play 2.4支持开箱即用的依赖注入控制器。我已成功使用构造函数注入来为我的控制器提供依赖项。但是,使用action composition时,不会注入标有@Inject
的字段。
有没有办法将依赖项注入复合动作?
控制器的示例代码:
public class Application extends Controller {
private DomainService ds;
@Inject
public Application(DomainService ds) {
this.ds = ds;
}
@Security.Authenticated(RandomAuthenticator.class)
public Result index() {
return ok();
}
}
复合动作的示例代码:
public class RandomAuthenticator extends Security.Authenticator {
@Inject private RandomService rs; // This field is never injected
@Override
public String getUsername(Context context) {
float randFloat = rs.nextFloat(); // Error! rs is always null
if (randFloat > 0.1) {
return "foo";
}
return null;
}
}
答案 0 :(得分:0)
您可以尝试使用课程'而不是现场注入。用Guice注入的构造函数:
public class RandomAuthenticator extends Security.Authenticator {
private RandomService rs;
@Inject
RandomAuthenticator(RandomService randomService) {
this.rs = randomService;
}
@Override
public String getUsername(Context context) {
float randFloat = rs.nextFloat(); // Error! rs is always null
if (randFloat > 0.1) {
return "foo";
}
return null;
}
}
答案 1 :(得分:0)
public class RandomAuthenticator extends Security.Authenticator {
private final RandomService rs;
public RandomAuthenticator(RandomService randomService) {
this.rs = randomService;
}
...
}
然后在Guice模块中使用@Provides方法:
@Provides
RandomAuthenticator provideRandomAuthenticator(RandomService randomService) {
return new RandomAuthenticator(randomService);
}