如何将某些内容注入到表单中

2023-12-07

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

Play Framework表单不可依赖注入,并且具有不同的范围userService,因此您无法通过注释将依赖项注入到登录表单中。尝试这个:

public String validate() {
    UserSvc userSvc = Play.application().injector().instanceOf(UserSvc.class);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将某些内容注入到表单中 的相关文章

随机推荐