问题描述
从 play 2.4.0 开始,我们可以使用 DI 框架了.
Since play 2.4.0, we can use a DI framework.
我正在尝试在我的应用中使用 DI.我将 jpa 查找器从模型类上的静态方法转移到服务层中的方法,然后注入到我的控制器中.
I am trying to use DI in my app. I moved my jpa finders from static methods on my models classes to methods in a service layer that I inject into my controllers.
我的主要问题是我有一些带有验证方法的表单,在我的验证方法中我使用了一些查找器.
My main problem is that I have some forms with a validate method and in my validate methode I use some finders.
例如在登录表单中,我使用User.authenticate"方法.现在我已经将这个静态方法替换为我的 UserSvc 上的一个新方法,我想将我的服务注入到我的表单中,但它不起作用.
For exemple in a login form I use a "User.authenticate" method. Now that I have replaced this static method to a new one on my UserSvc, I want to inject my service into my Form but it does not work.
似乎无法向 Form 中注入一些东西,那么我该如何解决我的问题
It seems that it is not possible to inject something into a Form so how can I solve my problem
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();
}
}
}
推荐答案
Play Framework
表单不可依赖注入并且与 userService
具有不同的作用域,因此您无法注入您的通过注释将依赖项转换为登录表单.试试这个:
Play Framework
forms are not dependency injectable and have different scope than userService
, thus you cannot inject your dependencies into Login form by annotation. Try this:
public String validate() {
UserSvc userSvc = Play.application().injector().instanceOf(UserSvc.class);
}
这篇关于如何将东西注入表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!