从玩 2.4.0 开始,我们可以使用 DI 框架。
我正在尝试在我的应用程序中使用 DI。我将我的 jpa 查找器从模型类上的静态方法移动到注入到控制器中的服务层中的方法。
我的主要问题是我有一些带有验证方法的表单,并且在我的验证方法中我使用了一些查找器。
例如,在登录表单中,我使用“User.authenticate”方法。现在我已经在我的 UserSvc 上将此静态方法替换为一个新方法,我想将我的服务注入到我的表单中,但它不起作用。
似乎无法将某些内容注入表单中,所以我该如何解决我的问题
public class MyController {
// Inject here can be used in controller methods but not in the form validate method
@Inject UserSvc userSvc;
public static class Login {
// Inject here is not filled : NPE
@Inject UserSvc userSvc;
public String email;
public String password;
public String validate() {
// How can I use userSvc here ?
}
}
@Transactional(readOnly = true)
public Result authenticate() {
Form<Login> loginForm = form(Login.class).bindFromRequest();
if (loginForm.hasErrors()) {
return badRequest(login.render(loginForm));
} else {
Secured.setUsername(loginForm.get().email);
return redirectConnected();
}
}
}