【问题标题】:How to inject something into a form如何在表单中注入一些东西
【发布时间】:2015-06-01 15:30:54
【问题描述】:

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

【问题讨论】:

    标签: java playframework playframework-2.4


    【解决方案1】:

    Play Framework 表单不是依赖注入的,并且与userService 具有不同的范围,因此您不能通过注释将依赖项注入登录表单。试试这个:

    public String validate() {
        UserSvc userSvc = Play.application().injector().instanceOf(UserSvc.class);
    }
    

    【讨论】:

    • Play.application() 自 2.5.0 版起已弃用。还有其他方法吗?
    • 在 2.5.x 版本中尝试 Play.current().injector().instanceOf(UserSvc.class);
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多